另一种获得控件的方法public View getChildAt(int index)
除了在布局文件里里面给控件设ID,然后通过findViewById(int id)方法得到控件外,还有另一种方法:
比如有这样一个布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:id="@+id/linearLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> </LinearLayout>我们没有为2个TextView设置ID,但是照样可以得到它们,方法如下LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout); TextView tv1 = (TextView) linearLayout.getChildAt(0); TextView tv2 = (TextView) linearLayout.getChildAt(1);
用getChildAt方法也可以得到控件