我已经调用了一个Activity从一个片段更新UI的方法,我得到一个无声的CalledFromWrongThreadException
告诉我Only the original thread that created a view hierarchy can touch its views
。从UI线程运行的Fragment中调用Activity方法吗?
我的活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
createDynamicView();
}
public void createDynamicView() {
// Create some View and attach that to a ViewGroup dynamically as below:
RelativeLayout rl = new RelativeLayout(this);
// ...
TextView textView = new TextView(this);
// ...
rl.addView(textView, layout_params1);
layout.addView(rl, layout_params2);
}
// Method called from Fragment
@Override
public void updateLayout() {
View v = layout.getChaildAt(index); // v is a TextView
// This line throws a silent Exception:
// android.view.ViewRootImpl$CalledFromWrongThreadException:
// Only the original thread that created a view hierarchy can touch its views
v.setBackgroundColor(Color.WHITE);
}
内部片段:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
parent = (SettingsInterface) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement SettingsInterface");
}
}
public void updateLayout() {
parent.updateLayout();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
webView = (WebView) view.findViewById(R.id.webView1);
// ...
textWebView.addJavascriptInterface(new JSInterface(getActivity()), "Android");
}
public class JSInterface {
@JavascriptInterface
public void updateLayout() {
updateLayout();
}
}
如果我把线下方runOnUiThread
块中:
runOnUiThread(new Runnable() {
@Override
public void run() {
v.setBackgroundColor(Color.WHITE);
}
});
我不会例外,但这个可能会在第一次UI更新后运行。 我想知道片段是否在与UI线程不同的线程中运行? 以及为什么这个例外是沉默?
请显示源代码如何从片段调用updateLayout方法 – 2015-01-31 20:35:10
我已更新问题。 – 2015-01-31 20:42:02
片段中的哪个方法执行updateLayout()仍然没有信息。请显示您的片段的更多代码 – 2015-01-31 20:44:50