安卓开发:组合View实现自定义View

来源:互联网 发布:淘宝联盟挣钱吗 编辑:程序博客网 时间:2024/06/01 08:13

其实在安卓中,还可以通过组合的方式实现自定义View【原生的控件实现惨不忍睹】

实现的效果如下:
这里写图片描述

自定义出标题栏。标题栏由一个按钮和一个textView组合而成。

新建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();        }    }}

在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就是this.setContentView(R.layout.activity_main);而已。就不贴出来了

1 0