我的演示文稿终于奏效了。我的第一个屏幕有一个主要的 activity
,第二个屏幕有一个 Presentation
。
我的问题是,我无法更改演示文稿 View 上的内容。
演示文稿显示在第二个屏幕上后,为什么我不能更改 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);
}
最佳答案
好吧,我查看了 LogCat。
异常(exception)是:
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 用于此类事情。
关于Android Presentation Class - 如何动态更改 Presentation View,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17432487/