android自定义控件学习笔记

来源:互联网 发布:手机我的世界枪械js 编辑:程序博客网 时间:2024/04/30 17:24

新建一个XML文件名字为Title.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:background="@drawable/ic_launcher" >    <Button        android:id="@+id/title_back"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_margin="5dip"        android:background="@drawable/ic_launcher"        android:text="Back"        android:textColor="#fff" />    <TextView        android:id="@+id/title_text"        android:layout_width="0dip"        android:layout_height="wrap_content"        android:layout_gravity="center"        android:layout_weight="1"        android:gravity="center"        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="5dip"        android:background="@drawable/ic_launcher"        android:text="Edit"        android:textColor="#fff" /></LinearLayout>

这个就是我们自定义的控件具体内容

新建一个TitleLayout 继承自LinearLayout

public class TitleLayout extends LinearLayout {    public TitleLayout(Context context, AttributeSet attrs) {        super(context, attrs);        LayoutInflater.from(context).inflate(R.layout.title, 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 v) {                ((Activity) getContext()).finish();            }        });        titleEdit.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                Toast.makeText(getContext(), "You clicked Edit button",                        Toast.LENGTH_SHORT).show();            }        });    }}

其中使用了LayoutInflater,先给他我们具体的自定义控件的Layout的ID,然后在传递给他一个父布局,父布局就是本身this。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="wrap_content" >    <com.example.firstdaima.TitleLayout ---引用自定义控件        android:layout_width="match_parent"        android:layout_height="wrap_content" >    </com.example.firstdaima.TitleLayout></LinearLayout>

这里写图片描述

0 0
原创粉丝点击