我尽了最大的努力开发一种聪明的方法来清理成堆的Blah blah = (Blah) this.findViewById(R.id.blah),否则会污染字段和我的小活动的onCreate()方法,为此,我觉得不应该对XML中定义的每个视图使用setContentView(),而应该使用getViewInflate().inflate()。
Activity.setContentView()在某种程度上是一种语法糖吗?它实际上是在为每个视图重复getViewInflate().inflate()吗?我读到一些东西说好像它们是一样的。
如果我可以通过查看代码得到答案,请告诉我。我查看了Activity.class,但只找到了评论。
发布于 2012-07-11 18:25:20
activity上的setContentView实际上调用了Activity使用的窗口上的setContentView,它本身所做的远不止是膨胀布局。
您可以做的是使用reflexion将视图映射到类字段。您可以下载一个执行此操作的实用程序类on Github。
它将解析布局中声明的所有视图,然后尝试在R.id类中查找与id对应的名称。然后,它将尝试在目标对象中查找具有相同名称的字段,并将其设置为相应的视图。
例如,如果你有一个这样的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</LinearLayout>它会自动将其映射到您活动中的textView1字段。
发布于 2012-07-12 19:05:57
我要把我的差劲的研究成果发出来。总之,Activity.setContentView()委托PhoneWindow.setContentView() ( Window的唯一具体类),在其中调用LayoutInflater.inflate(),所以我想说"setContentView() == ViewInflate().inflate()“并不是那么离谱。
public class Activity extends ContextThemeWrapper{
private Window mWindow;
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
initActionBar();
}
public Window getWindow() {
return mWindow;
}
}
public class PhoneWindow extends Window {
private LayoutInflater mLayoutInflater;
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
**mLayoutInflater.inflate(layoutResID, mContentParent);**
final Callback cb = getCallback();
if (cb != null) {
cb.onContentChanged();
}
}
}发布于 2012-07-11 17:59:14
实际上你是对的,有两种方法可以达到同样的效果:
1) setContentView(R.layout.layout);
2)
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.layout, null);
setContentView(v);你来决定哪一个更适合你。希望这能有所帮助。
https://stackoverflow.com/questions/11429865
复制相似问题