最近有些同学问我为什么activity有setContentView( int id ),为什么没有getContentView()这个方法呢?
这个我真没办法回答,但是我能告诉你怎么去拿activity布局文件中的根布局。
android其实有一个getRootView()的方法,但是通常拿不到id,这是为什么呢?这是因为拿到的getRootView 是在ContentView外的DecorView。在《Android群英传》中说到:Android的Window对象由PhoneWindow实现,
DecorView将显示内容呈现在PhoneWindow上,所有的View监听由
WindowManagerService接收,通过Activity对象回调onClickListener;
DecorView包含TitleView 和ContentView,
这就是为什么
requestWindowFeature(Window.FEATURE_NO_TITLE)要放在setContent之前。
要想拿到布局文件的视图id,可以用这种方法:
((ViewGroup)findViewById(android.R.id.content)).getChildAt(0);
空口无凭,以实验为证:
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.caoyujie.decorviewdemo.MainActivity">
<TextView
android:id="@+id/tv_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
测试代码
LinearLayout ll = (LinearLayout) findViewById(R.id.activity_main);
TextView tv1 = (TextView) findViewById(R.id.tv_1);
Log.e("TAG","xmlroot = " + ll.getId());
Log.e("TAG","RootView = " + tv1.getRootView().getId());
Log.e("TAG","DecorView = " + getWindow().getDecorView().getId());
Log.e("TAG","DecorView.getRootView() = " + getWindow().getDecorView().getRootView().getId());
Log.e("TAG","android.R.id.content.getChildAt(0) = " + ((ViewGroup)findViewById(android.R.id.content)).getChildAt(0).getId());
结果打印:
我们清楚地看到,只有((ViewGroup)findViewById(android.R.id.content)).getChildAt(0).getId()与根布局LinearLayout的id相同,其他都返回了-1。