自定义布局_用于标题栏

  1. 编写自定义控件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ff00">
<Button
    android:id="@+id/title_back"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    android:background="#00ffff"
    android:text="Back"
    android:textColor="#ffff"/>
    <TextView
        android:id="@+id/title_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:text="Title text"
        android:textColor="#fff"
        android:textSize="24sp"/>
    <Button
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        android:background="#00ff00"
        android:text="Edit"
        android:textColor="#fff"/>
</LinearLayout>
  1. 重写LinearLayout函数
package test.uicustomviews;
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.LinearLayout;
import android.widget.Toast;
 /////////////////
public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context,attrs);
        LayoutInflater.from(context).inflate(R.layout.activity_main,this);
        Button titleBack= (Button) findViewById(R.id.title_back);
        Button titleEdit= (Button) findViewById(R.id.title_edit);
        titleBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                ((Activity)getContext()).finish();
            }
        });
        titleEdit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(),"You Clicked Edit button",Toast.LENGTH_SHORT).show();
            }
        });
    }
}
  1. 布局中使用
    test.uicustomviews.TitleLayout部分,test.uicustomviews为包名,TitleLayout为代码文件名
<?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">
<test.uicustomviews.TitleLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"/>
</LinearLayout>
posted @ 2017-03-27 21:18  amours  阅读(528)  评论(0编辑  收藏  举报