1.要实现这个效果,用多个控件组合起来,要用到自定义控件
代码实现
1.自己写一个布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="52dp"
android:id="@+id/layout_title"
android:background="#ed4255">
<TextView
android:id="@+id/text_title"
android:ellipsize="marquee"
android:gravity="center_horizontal|center"
android:singleLine="true"
android:textSize="20dp"
android:textColor="#ffffffff"
android:text="标题栏"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="@+id/btn"
android:drawablePadding="6dp"
android:ellipsize="end"
android:gravity="center"
android:onClick="onClick"
android:paddingLeft="5dp"
android:singleLine="true"
android:text="返回"
android:textSize="18dp"
android:layout_width="60dp"
android:textColor="#ffffffff"
android:layout_height="match_parent" />
<Button
android:layout_alignParentRight="true"
android:id="@+id/btn1"
android:drawablePadding="6dp"
android:ellipsize="end"
android:gravity="center"
android:onClick="onClick"
android:paddingLeft="5dp"
android:singleLine="true"
android:text="提交"
android:textSize="18dp"
android:layout_width="60dp"
android:textColor="#ffffffff"
android:layout_height="match_parent" />
</RelativeLayout>
2.自己一个类继承RelativeLayout
3.直接在MainActivity中使用自定义控件public class TitleActivity extends RelativeLayout implements View.OnClickListener{ Context mycon; public TitleActivity(Context context) { this(context,null); } public TitleActivity(Context context, AttributeSet attrs) { this(context, attrs,0); } public TitleActivity(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //初始化布局 LayoutInflater inflater=LayoutInflater.from(context); //必须依赖父布局 参数1.自定义布局文件 2.父元素3.是否依赖父元素布局 View view = inflater.inflate(R.layout.aa, this, true); //找到控件 通过ID Button btn=view.findViewById(R.id.btn); Button btn1=view.findViewById(R.id.btn1); //设置点击事件 btn.setOnClickListener(this); btn1.setOnClickListener(this); //把上下文写成全局变量 mycon=context; } public void onClick(View v){ //判读点击事件 switch (v.getId()){ case R.id.btn: Toast.makeText(mycon,"返回",Toast.LENGTH_LONG).show(); break; case R.id.btn1: Toast.makeText(mycon,"提交",Toast.LENGTH_LONG).show(); break; } } }
<?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" android:orientation="vertical" tools:context="com.bwie.rikao_4.MainActivity"> <com.bwie.rikao_4.TitleActivity android:layout_width="match_parent" android:layout_height="wrap_content"></com.bwie.rikao_4.TitleActivity> </LinearLayout>