安卓开发:setContentView()和getViewInflate().inflate()有什么区别?

4
我尽力开发了一个巧妙的方法来清理掉在我的小活动的字段和onCreate()方法中污染的Blah blah = (Blah) this.findViewById(R.id.blah)堆,为此我觉得不应该使用setContentView()而应该使用getViewInflate().inflate()来定义XML中的每个视图。
Activity.setContentView()是一种语法糖,实际上对于XML中的每个视图都进行了getViewInflate().inflate()操作?我读到了一些说它们是相同的东西的内容。
如果我可以通过查看代码获得答案,请告诉我。我检查了Activity.class,但只找到注释。

1
这个 getViewInflate() 方法在哪里?我在 http://developer.android.com/reference/android/app/Activity.html 上没有看到它。 - sdabet
抱歉,应该是 ViewInflate.inflate() - Quv
3个回答

2
您的Activity上的setContentView实际上调用了活动使用的窗口上的setContentView,它本身做了比仅仅填充布局更多的事情。
您可以使用反射将视图映射到类字段。您可以从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字段。

谢谢。它们真的很有趣。对于我来说,一个问题是性能,可能是因为它调用一个方法搜索属于android.R.id.contentViewGroup中的每个View。也许我会避免使用setContentView()并定义自己的方法,这样我可以在每次执行ViewInflate.inflate()时将View分配给变量。 - Quv

2

我在发布我的不太好的研究。简而言之,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();
        }
    }
}

0

其实你是对的,有两种方法可以实现同样的效果:

1)setContentView(R.layout.layout);

2)

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View v = inflater.inflate(R.layout.layout, null);
setContentView(v);

你可以自行决定哪种方式更适合你。希望这能帮到你。


抱歉我的问题表述不够清晰。我怀疑在setContentView()方法的定义中,实际上使用了ViewInflate.inflate(),想知道这是否属实。也许我应该更详细地阐述我的问题…… - Quv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接