继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

如何打造一个标题栏

喵喔喔
关注TA
已关注
手记 388
粉丝 101
获赞 605

好啦,如何打造一个属于自己的标题栏呢?

首先已定义一个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();
    }
}

大功告成

5b78f6f800017e8503100572.jpg

但是有一个问题,做一个页面还好,但是每个页面都要求呢,那岂不是要重复的代码写很多遍?这里有一个方法可以解决,那些上班迟到下班却又很准时的就是这样做的

写一个类 继承自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;
        }
    }
}

原文链接:http://www.apkbus.com/blog-946024-77389.html

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP