组合控件,标题栏 (自定义view)

1.创建一个类,然后继承布局

public class MyTitleView extends LinearLayout{
    private View titleViewGroup;
    private TextView titleView;
    private Button leftbut;
    private Button rightbut;
    public MyTitleView(Context context) {
        super(context);
    }
    public MyTitleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        //去获取属性
        TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTitleView, 0, 0);
        //根据声明的属性从typedArray中取值
        String titleText = typedArray.getString(R.styleable.MyTitleView_title_text);
        String leftText = typedArray.getString(R.styleable.MyTitleView_left_btn_text);
        String rightText = typedArray.getString(R.styleable.MyTitleView_right_btn_text);
        int titleColor = typedArray.getColor(R.styleable.MyTitleView_title_color, Color.BLACK);
        //加载一个view到当前这个view
        titleViewGroup = inflate(context, R.layout.title_layout,this);
        titleView = titleViewGroup.findViewById(R.id.tv_title);
        leftbut=   titleViewGroup.findViewById(R.id.btn_left);
        rightbut=titleViewGroup.findViewById(R.id.btn_right);
        //设置中间view的文本内容
        titleView.setText(titleText);
        titleView.setTextColor(titleColor);
        titleView.setText(leftText);
        titleView.setText(rightText);
    }

2   创建一个布局 ,实习标题栏中要是实现的控件

title_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="match_parent"
    android:orientation="horizontal">
    <Button
        android:id="@+id/btn_left"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <TextView
        android:id="@+id/tv_title"
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent" />
    <Button
        android:id="@+id/btn_right"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

3.在values文件夹下创建一个xml(我创建了一个attrs)

<resources>
    <!--declare-styleable 声明一个自定义-->
    <declare-styleable name="MyTitleView">
        <attr name="title_text" format="string"></attr>
        <attr name="title_color" format="color"/>

        <attr name="left_btn_text" format="string"/>

       <attr name="right_btn_text"  format="string"/>

    </declare-styleable>

</resources>

4  在实现的xml中实现,attrs中的属性的值

<com.example.thinkpad.myapplication1.MyTitleView
        android:layout_width="match_parent"
        android:layout_height="60dp"
        app:title_text="首页"
        app:title_color="@color/colorPrimaryDark"
        app:left_btn_text="返回"
         app:right_btn_text="注册">


猜你喜欢

转载自blog.csdn.net/wsj19970717/article/details/80644069