您的位置:首页 > 移动开发 > Android开发

自定义View---header(标题栏)

2017-07-21 21:51 204 查看

布局文件,xml代码

<?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="50dp"
android:background="@color/colorPrimary"
android:orientation="horizontal">

<ImageView
android:id="@+id/back"
android:src="@drawable/ic_back"
android:padding="10dp"
android:layout_width="50dp"
android:layout_height="50dp" />

<TextView
android:id="@+id/title"
android:layout_weight="1"
android:text="题目"
android:textSize="20sp"
android:gravity="center"
android:textColor="@color/white"
android:layout_width="wrap_content"
android:layout_height="match_parent" />

<ImageView
android:id="@+id/fun"
android:src="@mipmap/ic_search_white"
android:padding="6dp"
android:layout_width="50dp"
android:layout_height="50dp" />

</LinearLayout>


资源文件,attrs代码

<declare-styleable name="Header">
<attr name="header_back" format="integer"/>
<attr name="header_title" format="string"/>
<attr name="header_fun" format="integer"/>
</declare-styleable>


java代码

public class Header extends LinearLayout{
private Context context;
private AttributeSet attrs;
private String title;
private Integer back;
private Integer fun;
private View v;

ImageView iv_back;
TextView tv_title;
ImageView iv_fun;

public Header(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
this.attrs = attrs;
initView();
}

private void initView(){
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.Header);
title = typedArray.getString(R.styleable.Header_header_title);
back = typedArray.getInteger(R.styleable.Header_header_back,0);
fun = typedArray.getInteger(R.styleable.Header_header_fun,0);
typedArray.recycle();

v = LayoutInflater.from(context).inflate(R.layout.view_header,null);
iv_back = (ImageView) v.findViewById(R.id.back);
tv_title = (TextView) v.findViewById(R.id.title);
iv_fun = (ImageView) v.findViewById(R.id.fun);

setTitle(title);

LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
addView(v,params);

iv_back.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
((Activity)context).finish();
}
});
}

//设置题目
public void setTitle(String title){
tv_title.setText(title);
}

//设置返回按钮
public void setOnBackClickListener(OnClickListener o){
iv_back.setOnClickListener(o);
}

//设置fun按钮
public void setOnFunClickListener(OnClickListener o){
iv_fun.setOnClickListener(o);
}

}


使用

<com.view.Header
android:id="@+id/header"
app:header_title="用户"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android