Android Presentation Class - 如何动态更改Presentation View

时间:2013-07-02 17:54:50

标签: android screen presentation

我的演讲终于工作了。我的第一个屏幕有一个主activity,第二个屏幕有一个Presentation。 我的问题是,我无法更改演示文稿视图中的内容。

为什么在第二个屏幕上显示演示文稿后无法更改TextView? 调用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);

}

2 个答案:

答案 0 :(得分:2)

好吧,我查看了LogCat。 例外是:

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

MainActivity中的代码在另一个线程上运行。要从这里做UI工作,我需要使用runOnUiThread。我在this回答中找到了这个解决方案。

我的changeText方法现在看起来像这样:

public void changeText (String s) {

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

感谢您的帮助!现在我知道如何使用LogCat做类似的事情。

答案 1 :(得分:1)

您遇到此问题是因为演示文稿的上下文与包含活动的内容不同:

  

演示文稿在创建时与目标显示相关联   并根据配置其上下文和资源配置   显示指标。

     

值得注意的是,演示文稿的上下文与上下文不同   它的含有活动。膨胀a的布局是很重要的   使用演示文稿自己演示和加载其他资源   上下文,以确保资产的正确大小和密度   目标显示已加载。

希望这也证明了你提到的解决方案。

相关问题