一手遮天 Android - view(布局类): 通过 include 静态加载布局文件
一手遮天 Android - view(布局类): 通过 include 静态加载布局文件
示例如下:
/view/layout/IncludeDemo1.java
/**
* 演示如何通过 include 静态加载布局文件(参见 /res/layout/activity_view_layout_includedemo1.xml)
*/
package com.webabcd.androiddemo.view.layout;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TextView;
import com.webabcd.androiddemo.R;
public class IncludeDemo1 extends AppCompatActivity {
private TextView mTextView1;
private TextView mTextView2;
private TextView mTextView3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_layout_includedemo1);
mTextView1 = findViewById(R.id.textView1);
mTextView2 = findViewById(R.id.textView2);
mTextView3 = findViewById(R.id.textView3);
sample();
}
private void sample() {
mTextView1.setBackgroundColor(Color.RED);
mTextView2.setBackgroundColor(Color.GREEN);
mTextView3.setBackgroundColor(Color.BLUE);
}
}
/layout/activity_view_layout_includedemo1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="main_textView1" />
<!--
通过 include 导入指定的 layout 文件
在 java 中可以直接通过 findViewById() 找到 include 进来的控件
如果主布局和 include 布局中有重名的控件,则以最先找到的为准(本例中主布局的 textView1 控件在 include 布局的 textView1 控件的前面,所以 findViewById() 获取到的是主布局的 textView1 控件)
-->
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/view_view_layout_includedemo1" />
</LinearLayout>