自定义控件 标题栏

先写一个你要的布局文件作为标题栏
head_title.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=”match_parent”
android:orientation=”horizontal”>
ImageView
android:id=”@+id/bt_back”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/icon_return_back”/>
TextView
android:layout_width=”0dp”
android:layout_height=”wrap_content”
android:layout_weight=”1”
android:layout_marginLeft=”20dp”
android:gravity=”center”
android:text=”标题栏”/>
Button
android:id=”@+id/bt_edit”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Edit”/>

再写一个类继承LinearLayout

构造方法 必须是public
(必须调用父类的super(context,attributes))

package com.example.dy.myapplication;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

/**
* Created by dy on 2015/4/15.
*/
public class DLinearLayout extends LinearLayout implements View.OnClickListener{
private ImageView bt_back ;
private Button bt_exit ;
public DLinearLayout(Context context,AttributeSet attributeSet){
// 不许声明public
super(context,attributeSet); // 调用父类的构造方法 这个是必须的
View view = LayoutInflater.from(context).inflate(R.layout.head_title,this);
// 加载布局文件
bt_back =(ImageView)view.findViewById(R.id.bt_back); // 得到控件
bt_exit = (Button) view.findViewById(R.id.bt_edit);
bt_back.setOnClickListener(this);
bt_exit.setOnClickListener(this);
}

@Override
public void onClick(View v) {
// 触发事件
      switch (v.getId()){
          case R.id.bt_back:
              ((Activity) getContext()).finish();
              break ;
          case R.id.bt_edit:
              Toast.makeText(getContext(),"this is Exit",Toast.LENGTH_SHORT).show();
              break ;

      }
}

}

布局中调用这个就可以了:

RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:tools=”http://schemas.android.com/tools” android:layout_width=”match_parent”
android:layout_height=”match_parent” android:paddingLeft=”@dimen/activity_horizontal_margin”
android:paddingRight=”@dimen/activity_horizontal_margin”
android:paddingTop=”@dimen/activity_vertical_margin”
android:paddingBottom=”@dimen/activity_vertical_margin” tools:context=”.MainActivity”>
com.example.dy.myapplication.DLinearLayout

android:layout_width="match_parent"
android:layout_height="match_parent">

</com.example.dy.myapplication.DLinearLayout>

这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章