自定义布局文件:
<?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="wrap_content"
android:background="#ff80aa">
<Button
android:id="@+id/button_title01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="back"
android:textColor="@color/colorPrimary"
android:background="#66ffff"
android:layout_margin="5dp"
android:layout_gravity="center"/>
<EditText
android:id="@+id/ET_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:maxLines="1"
android:gravity="center"
android:hint="Title text"
android:textColor="@color/colorPrimary"
android:textSize="24sp"/>
<Button
android:id="@+id/button_title02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edit"
android:textColor="@color/colorPrimary"
android:background="#66ffff"
android:layout_margin="5dp"
android:layout_gravity="center"/>
</LinearLayout>
效果图
创建自定义控件:
这里重写了LinearLayout 带有两个参数的构造方法
public class TitleLayout extends LinearLayout {
public TitleLayout (Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.activity_title,this);//第一个参数是要加载的布局文件id,第二个参数this表示父布局为TitleLayout
//设置点击事件
Button button1=(Button) findViewById(R.id.button_title01);
Button button2=(Button) findViewById(R.id.button_title02);
final EditText editText=(EditText)findViewById(R.id.ET_title);
button1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)getContext()).finish();
}
});
button2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String data=editText.getText().toString();
Toast.makeText(getContext(), "you click Edit button:"+data, Toast.LENGTH_SHORT).show();
}
});
}
}
在布局文件中添加这个自定义控件(自定义标题栏):
在first_layout.xml布局文件中添加以下代码,引入自定义控件:在添加自定义控件的时候,我们需要指明控件完整的类名,包名也不可省
如果导入的是布局文件使用:include标签官方文档
<com.example.activitytest.TitleLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
我们还需要取消自带的标题栏:
在FirstActivity中添加以下代码,屏蔽自带标题栏
//隐藏标题栏
ActionBar actionBar=getSupportActionBar();
if (actionBar!=null)
{
actionBar.hide();
}
最终效果图: