include的简单使用

1.事前准备

<!--在res/values/styles.xml中-->
<!--设置样式-->
<style name="RemoteButton">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:layout_margin">3dp</item>
        <item name="android:textColor">@drawable/button_text_action</item>
        <item name="android:background">@drawable/button_shape_shadowed</item>
</style>
<!--res/layout/include_button-->
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        style="@style/RemoteButton"
        />
    <Button
        style="@style/RemoteButton"
        />
    <Button
        style="@style/RemoteButton"
        />
</TableRow>
<!--res/layout/main.xml  应用linclude-->
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:stretchColumns="*"
    android:id="@+id/fragment_remove_control_table">
    <include
        android:layout_weight="1"
        layout="@layout/include_fragment_remove_control"
        />
    <include
        android:layout_weight="1"
        layout="@layout/include_fragment_remove_control"/>
    <include
        android:layout_weight="1"
        layout="@layout/include_fragment_remove_control"/>
    <include
        android:layout_weight="1"
        layout="@layout/include_fragment_remove_control"/>
</TableLayout>

2.应用Java代码获取include内容

TableLayout tableLayout = (TableLayout)v.findViewById(R.id.fragment_remove_control_table);
//利用getChild()方法获取控件内部的控件
for (int i=2; i<tableLayout.getChildCount()-1; ++i){
            TableRow row = (TableRow)tableLayout.getChildAt(i);
            for (int j=0; j<row.getChildCount(); ++j){
                Button button = (Button)row.getChildAt(j);
                button.setText(String.valueOf((i-2)*3+j+1));
                button.setOnClickListener(numberOnClick);
            }
}
原文地址:https://www.cnblogs.com/rookiechen/p/5253935.html