好啦,如何打造一个属于自己的标题栏呢?
首先已定义一个layout文件啦
<?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"> <Button android:id="@+id/btn_return" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="5dp" android:text="return" /> <TextView android:id="@+id/textview_title" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_weight="1" android:gravity="center" android:text="title" android:textSize="20dp" /> <Button android:id="@+id/button_edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="5dp" android:text="edit" /> </LinearLayout>
这个文件没什么内涵,就是画了两个button一个textview
ok,下一步,在主布局文件中加入这个layout文件。
<include layout="@layout/layout_title"/>
下一步再把默认的标题栏去掉
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar=getSupportActionBar();
if (actionBar!=null){
actionBar.hide();
}
}大功告成
但是有一个问题,做一个页面还好,但是每个页面都要求呢,那岂不是要重复的代码写很多遍?这里有一个方法可以解决,那些上班迟到下班却又很准时的就是这样做的
写一个类 继承自linerlayout
在 主布局文件中作为一个组件加载
<com.example.zvt_110.myapplication.TitleLayout android:layout_width="match_parent" android:layout_height="wrap_content" />
public class TitleLayout extends LinearLayout implements View.OnClickListener {
Button button_edit;
public TitleLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.layout_title, this);
button_return = findViewById(R.id.btn_return);
button_edit = findViewById(R.id.button_edit);
button_return.setOnClickListener(this);
button_edit.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_edit:
Toast.makeText(getContext(), "edit", Toast.LENGTH_SHORT).show();
break;
case R.id.btn_return:
Toast.makeText(getContext(), "return", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}

随时随地看视频