第一种情况:include没有设置id
include里面的所有控件都是被当成xml中布局的一部分来使用,xml中里面的控件怎么使用 ,include里面的控件怎么使用。
即把include里面的控件当成主xml里面的正常控件即可。
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
layout="@layout/include_child_layout" />
setContentView(R.layout.activity_main);
ViewUtils.inject(this);
第二种情况:include设置了id
如果include指定了id的话,就不能直接把它里面的控件当成主xml中的控件来直接获得了,必须先获得这个xml布局文件,再通过布局文件findViewById来获得其子控件
<include
android:id="@+id/include_father"
layout="@layout/include_child_layout" />
@ViewInject(R.id.include_father)
private LinearLayout include_father;//ViewUtils.inject(this);加载include的整体布局
setContentView(R.layout.activity_main); //界面
ViewUtils.inject(this);//加载主界面,此时加载id为in_types_inner的include整体布局,注意顺序别错了
ViewUtils.inject(include_father);//再次加载include的布局
public class MainActivity extends Activity {
@ViewInject(R.id.include_01)
private LinearLayout include_01;
@ViewInject(R.id.ll_child_02_father)
private LinearLayout ll_child_02_father;
@ViewInject(R.id.tv_child_01_child)
private TextView tv_child_01_child;
@ViewInject(R.id.tv_child_02_child)
private TextView tv_child_02_child;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewUtils.inject(this);
ViewUtils.inject(include_01);
include_01.setBackgroundColor(Color.RED);
ll_child_02_father.setBackgroundColor(Color.CYAN);
tv_child_01_child.setText("tv_child_01_childtv_child_01_child");
tv_child_02_child.setText("tv_child_02_childtv_child_02_child");
}
<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"
tools:context="${relativePackage}.${activityClass}" >
<include
android:id="@+id/include_01"
android:layout_below="@+id/test"
android:layout_width="match_parent"
android:layout_height="20dp"
layout="@layout/layout_child_01"/>
<include
android:layout_below="@+id/include_01"
android:layout_width="match_parent"
android:layout_height="20dp"
layout="@layout/layout_child_02"/>
</RelativeLayout>