3

私のプレゼンテーションはついに機能しています。activity最初の画面用に1 つのメインとPresentation、2 番目の画面用に 1 つのメインがあります。私の問題は、プレゼンテーション ビューのコンテンツを変更できないことです。

TextViewプレゼンテーションが 2 番目の画面に表示された後に変更できないのはなぜですか? changeText("Test123")でメソッドを呼び出すとMainActivity、アプリがクラッシュします。

public class MainActivity extends Activity {

    private PresentationActivity presentationActivity;

    protected void onCreate(Bundle savedInstanceState) {    

        super.onCreate(savedInstanceState);  


        // init Presentation Class

        DisplayManager displayManager = (DisplayManager) this.getSystemService(Context.DISPLAY_SERVICE);
        Display[] presentationDisplays = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION);
        if (presentationDisplays.length > 0) {
            // If there is more than one suitable presentation display, then we could consider
            // giving the user a choice.  For this example, we simply choose the first display
            // which is the one the system recommends as the preferred presentation display.
            Display display = presentationDisplays[0];
            PresentationActivity presentation = new PresentationActivity(this, display);
            presentation.show();

            this.presentationActivity =  presentation;    
        }
    }

    public void changeText (String s) {

        this.presentationActivity.setText(s);

    }
}



public class PresentationActivity extends Presentation {

    private TextView text;



    private PresentationActivity presentation;


public PresentationActivity(Context outerContext, Display display) {
    super(outerContext, display);
    // TODO Auto-generated constructor stub

}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     

    setContentView(R.layout.activity_presentation);   

    TextView text = (TextView) findViewById(R.id.textView1);

    this.text = text;
    // works fine:
    text.setText("test");      

}

public void setText(String s){

    // error
    this.text.setText(s);

}
4

2 に答える 2

3

さて、LogCat を調べました。例外は次のとおりです。

E/AndroidRuntime(13950): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

私のコードはMainActivity別のスレッドで実行されます。ここから UI 作業を行うには、 を使用する必要がありますrunOnUiThreadこの回答で見つけたこの解決策。

私のchangeTextメソッドは次のようになります。

public void changeText (String s) {

        runOnUiThread(new Runnable() {
          public void run() {
              presentationActivity.setImageView(position);
          }
    });
}

助けてくれてありがとう!これで、そのようなことに LogCat を使用する方法がわかりました。

于 2013-07-03T15:03:59.950 に答える
1

プレゼンテーションのコンテキストが含まれているアクティビティのコンテキストと異なるため、この問題が発生しました。

プレゼンテーションは、作成時にターゲット ディスプレイに関連付けられ、ディスプレイのメトリックに従ってそのコンテキストとリソース構成を構成します。

特に、プレゼンテーションのコンテキストは、それを含むアクティビティのコンテキストとは異なります。プレゼンテーションのレイアウトを拡張し、プレゼンテーション自体のコンテキストを使用して他のリソースをロードして、ターゲット ディスプレイに適切なサイズと密度のアセットがロードされるようにすることが重要です。

これがあなたの言及した解決策も正当化することを願っています。

于 2014-06-06T10:04:25.253 に答える