Android開発:ビューを組み合わせてカスタムビューを実現

実際、Androidでは、組み合わせによってカスタムビューを実装することもできます[ネイティブコントロールの実装はひどいです]

達成された効果は次のとおりです。
ここに写真の説明を書いてください

タイトルバーをカスタマイズします。タイトルバーは、ボタンと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);それだけです。投稿しません

おすすめ

転載: blog.csdn.net/new_Aiden/article/details/50861313