自定义带返回按钮的标题

1,项目中基本每个页面都要用到返回按钮以及标题,每次使用每次写就变的很麻烦,也没有必要,所以今天要自定义一个TitleView方便使用。

首先,要写个布局文件:里面放一个返回按钮以及一个标题

<?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">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <ImageView
            android:id="@+id/back_img"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_centerVertical="true"
            android:layout_marginLeft="5dp"
            android:background="@mipmap/back" />

        <TextView
            android:id="@+id/title_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="标题"
            android:textSize="20sp" />
    </RelativeLayout>
</LinearLayout>

然后再自定义一个TitleView类,其中包含返回按钮的回调,以及标题的设置

public class TitleView extends FrameLayout {
    private TextView titleText;
    private ImageView back;
    private setBackClickListener setBackClickListener;

    public TitleView(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title_layout, this);
        titleText = findViewById(R.id.title_name);
        back = findViewById(R.id.back_img);
        back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setBackClickListener.backClick();
            }
        });
    }

    /**
     * 设置标题
     *
     * @param text
     */
    public void setTitleText(String text) {
        titleText.setText(text);
    }

    /**
     * 隐藏返回按钮
     */
    public void hideBackImage() {
        back.setVisibility(View.GONE);
    }

    public void setBackImageListener(setBackClickListener setBackClickListener) {
        this.setBackClickListener = setBackClickListener;
    }

    public interface setBackClickListener {
        void backClick();
    }

}

最后是使用:在布局文件;

<com.newdicooker.tempetek.toastdemo.TitleView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="50dp" />

在代码中设置标题内容以及返回监听

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.title)
    TitleView title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        setListener();

    }

    private void setListener() {
        title.setTitleText("你好啊");
        title.setBackImageListener(new TitleView.setBackClickListener() {
            @Override
            public void backClick() {
                finish();
            }
        });
    }
这样就打造好自己的自定义布局了

猜你喜欢

转载自blog.csdn.net/m0_37177456/article/details/80078994