`

自定义控件

 
阅读更多

1.自定义布局

新建一个title.xml的Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="1">

 

    <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:text="Back"
        android:textColor="#fff"
        />

    <TextView
        android:id="@+id/title_text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textColor="#fff"
        android:textSize="24sp"
        android:layout_weight="1"
        android:text="Title Text"
        android:gravity="center" />

    <Button
        android:id="@+id/title_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:text="Edit"
        android:textColor="#fff"
        android:layout_gravity="center"
        />
</LinearLayout>

显示:

【Back】Title Text 【Edit】

 

在其他Layout中可以使用<include layout="@layout/title" />包含进去

 

2.自定义控件

第一步:新建控件类

public class TitleLayout extends LinearLayout {
    public TitleLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.title, this); //相当于findViewById,获得title.xml

 

第二步:

在MainActivity.xml中添加TitleLayout引用

<com.example.test.test.TitleLayout
        anroid:layout_width="match_parent"
        anroid:layout_height="wrap_content">

  </com.example.test.test.TitleLayout>

第三步:

在TitleLayout类中添加按钮点击事件

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_LONG).show();
            }
        });

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics