一、先设置抽取出一个公共的控件,这里面我们用Toolbar
<?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" xmlns:app="http://schemas.android.com/apk/res-auto"> <androidx.appcompat.widget.Toolbar android:id="@+id/tool_bar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /> </LinearLayout>
二、在另外一个布局中通过include标签引入上面已经写好的layout布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".activity.IncludeActivity"> <include android:id="@+id/tool_include" layout="@layout/include_toolbar"/> </LinearLayout>
三、最重要的一步,获取include标签中的子控件中的属性
public class IncludeActivity extends AppCompatActivity { private Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_include); //第一个id是我们给include标签设置的id,第二个id就是公共的layout中的具体控件的id toolbar = findViewById(R.id.tool_include).findViewById(R.id.tool_bar); TextView textView = new TextView(this); textView.setText("我是Toolbar"); toolbar.addView(textView); setSupportActionBar(toolbar); } }