view对象句柄的获取是非常重要的,一个view对象,一旦我们获取到了她的句柄,那么,我们就可以对她进行任何操作了。而获取句柄,在android开发中,主要是采用findviewbyid的方法,来得到她的ID值。
在android的view官方文档中,我们发现有如下说明:
也就是说,对于一个view的ID值,我们可以认为这就是一个获取她句柄的索引值,而我们通过此ID值得到此view,主要是通过Activity的findViewById()方法和View.findViewById()方法:
Activity中findViewById说明:
我们一般在activity中使用findViewById的方法:
此方法,大家经常使用,我就不详细说明了。
此方法的本质是使用父控件来根据子控件的ID值,读取子控件的句柄。
(1)xml布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <LinearLayout android:id="@+id/ll" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/tv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="activity-findviewbyid" /> </LinearLayout> </RelativeLayout>
public class MainActivity extends Activity { private TextView tv; private LinearLayout ll; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { // TODO Auto-generated method stub tv = (TextView)findViewById(R.id.tv); ll = (LinearLayout)findViewById(R.id.ll); ll.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { // TODO Auto-generated method stub ((TextView)ll.findViewById(R.id.tv)).setText("view--findviewbyid"); } }); }
tv = (TextView)findViewById(R.id.tv);
View的findViewById使用方法:
((TextView)ll.findViewById(R.id.tv)).setText("view--findviewbyid");
可能有的人,看完这篇文章,会说,这个有什么不会的,非常简单啊,我早就会用了。是的,是非常简单,但是,这在一些非常复杂的界面中,特别是一些不是用布局文件,而动态生成的界面,有时候是非常有用的。给大家看一下,我在代码中使用的样例吧,这可能不是怎么符合代码写作规范,但是这对快速实现需求,确实是一个利器:
((TextView)(mAddFieldFooter.findViewById(R.id.add_text))).setText(R.string.wt_add_email);
((EditText)(((LinearLayout)(mOrganizationSectionViewContainer.getChildAt(0).findViewById(R.id.editors))).getChildAt(0))).setHint(getResources().getString(R.string.add_organization));
这个点也告诉我们,当我们自己写的view,如果需要后期修改,那么最好是给她id值吧,这样,会给以后的代码维护和修改提供非常多的便利。