Android Development: Combine Views to Realize Custom Views

In fact, in Android, you can also implement a custom View through combination [the implementation of native controls is terrible]

The achieved effect is as follows:
Write picture description here

Customize the title bar. The title bar is composed of a button and a textView.

Create a new my_title.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#236598">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="返回"
        android:textColor="#000000"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:text="标题栏"
        android:textSize="20dp" />

</RelativeLayout>

MyTitle.java:

package com.example.aiden.myapplication;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * Created by Aiden on 2016/3/11.
 */
public class MyTitle extends RelativeLayout implements View.OnClickListener{
    private Button button;
    public MyTitle(Context context, AttributeSet attrs) {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.my_title, this);
        button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v == button) {
            Toast.makeText(this.getContext(), "您按了返回按钮", Toast.LENGTH_LONG).show();
        }
    }
}

In activity_main.xml:

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.aiden.myapplication.MyTitle
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity is this.setContentView(R.layout.activity_main); that's it. I won't post it

Guess you like

Origin blog.csdn.net/new_Aiden/article/details/50861313