1.引入布局文件
右键res/layout文件夹,创建Layout Resource File,命名为title。配置代码如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#00ff00">
<Button
android:id="@+id/back_button"
android:text="返回"
android:textSize="30sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="60dp" />
<TextView
android:id="@+id/text_view"
android:text="标题"
android:textSize="30sp"
android:layout_gravity="center"
android:gravity="center"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="60dp" />
<Button
android:id="@+id/edit_button"
android:text="编辑"
android:textSize="30sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="60dp" />
</LinearLayout>
android:layout_gravity控制控件内容排列方式。
android:gravity控制控件排列方式。
然后在通过<include>标签引入,代码如下:
<?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">
<include layout="@layout/title" />
</LinearLayout>
在引用控件的Activity中,去掉标题栏,代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
}
}
2.添加方法
修改引入布局文件,代码如下:
<?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">
<top.xiexiaodong.uidemo.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
创建TitleLayout类,继承LinearLayout类,在这个类里面实现控件事件,代码如下:
public class TitleLayout extends LinearLayout {
public TitleLayout(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
Button backButton = (Button) findViewById(R.id.back_button);
Button editButton = (Button) findViewById(R.id.edit_button);
backButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity) getContext()).finish();
}
});
editButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(), "你点击了编辑按钮", Toast.LENGTH_SHORT).show();
}
});
}
}