Android findViewById(int)检索的视图上的操作未反映在UI上
我完全不知道这里发生了什么。用户界面上不会反映对Activity.findViewById(int)检索的视图的任何操作 字符串“立即设置此文本!”(请参见下文)应设置为文本标签的文本,但它不是。它只显示布局XML文件中定义的初始文本 加载屏幕类别:Android findViewById(int)检索的视图上的操作未反映在UI上,android,layout,Android,Layout,我完全不知道这里发生了什么。用户界面上不会反映对Activity.findViewById(int)检索的视图的任何操作 字符串“立即设置此文本!”(请参见下文)应设置为文本标签的文本,但它不是。它只显示布局XML文件中定义的初始文本 加载屏幕类别: public class LoadingScreen extends Screen { private TextView textLabel; public LoadingScreen(Screen parent) {
public class LoadingScreen extends Screen {
private TextView textLabel;
public LoadingScreen(Screen parent) {
super(R.layout.screen_loading, parent);
this.textLabel = (TextView) getActivity().findViewById(R.id.loading_text_label);
this.textLabel.setText("Set this text now!");
}
}
public class Screen {
private int layoutResourceId;
private int contentResourceId;
public Screen(int layoutResourceId, Screen parent) {
this.layoutResourceId = layoutResourceId;
this.parent = parent;
loadLayout();
}
private void loadLayout() {
if (this.parent == null) {
this.uiManager.getActivity().setContentView(this.layoutResourceId);
}
else {
View view = LayoutInflater.from(getActivity()).inflate(this.layoutResourceId, null);
ViewGroup container = (ViewGroup) getActivity().findViewById(this.parent.contentResourceId);
container.removeAllViews();
container.addView(view);
}
}
}
屏幕类别:
public class LoadingScreen extends Screen {
private TextView textLabel;
public LoadingScreen(Screen parent) {
super(R.layout.screen_loading, parent);
this.textLabel = (TextView) getActivity().findViewById(R.id.loading_text_label);
this.textLabel.setText("Set this text now!");
}
}
public class Screen {
private int layoutResourceId;
private int contentResourceId;
public Screen(int layoutResourceId, Screen parent) {
this.layoutResourceId = layoutResourceId;
this.parent = parent;
loadLayout();
}
private void loadLayout() {
if (this.parent == null) {
this.uiManager.getActivity().setContentView(this.layoutResourceId);
}
else {
View view = LayoutInflater.from(getActivity()).inflate(this.layoutResourceId, null);
ViewGroup container = (ViewGroup) getActivity().findViewById(this.parent.contentResourceId);
container.removeAllViews();
container.addView(view);
}
}
}
此外,以下规定适用:
不会抛出Activity.findViewById(int)
NullPointerException
- 根据
返回Looper.getMainLooper().getThread()==thread.currentThread()
的事实,代码在UI线程上运行true
如何修复它?如果未引发任何
NullPointerException
,这意味着内容视图已加载,UI应更新要更改的元素(例如,调用setText(CharSequence)
以更改文本)
上面的代码片段看起来不错。问题不在代码段中,但方法
loadLayout()
被调用了两次,这一事实导致了内容视图被重新加载的问题,将XML布局文件中的所有元素重置为它们的初始值(例如,使用android:text=“我自己的初始值”
).在设置如下文本后尝试使文本视图无效:this.textlab.invalidate();