溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

android中自定義View之復(fù)合控件的示例分析

發(fā)布時(shí)間:2021-06-11 10:35:10 來(lái)源:億速云 閱讀:136 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章給大家分享的是有關(guān)android中自定義View之復(fù)合控件的示例分析的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。

復(fù)合控件可以很好地創(chuàng)建出具有重用功能的控件集合。

很多的APP都有一些共通的UI界面,為了統(tǒng)一應(yīng)用程序的風(fēng)格,下面我們就以一個(gè)Topbar為實(shí)例講解復(fù)合控件。
實(shí)現(xiàn)效果如圖:

android中自定義View之復(fù)合控件的示例分析

第一步:定義屬性

在res資源目錄的values目錄下創(chuàng)建一個(gè)attrs.xml屬性定義文件,為一個(gè)View提供可自定義的屬性。
代碼中,通過(guò)標(biāo)簽聲明了自定義屬性,并通過(guò)name屬性來(lái)確定引用的名稱。

<?xml version="1.0" encoding="utf-8"?> <resources>
    <declare-styleable name="TopBar">
        <attr name="titleText" format="string"/>
        <attr name="titleSize" format="dimension"/>
        <attr name="titleTextColor2" format="color"/>
        <attr name="leftTextColor" format="color"/>
        <attr name="leftBackground" format="reference|color"/>
       <!--按鈕的背景可以指定為具體顏色,也可以一張圖片,所以使用“|”來(lái)分隔不同的屬性-->
        <attr name="leftText" format="string"/>
        <attr name="rightTextColor" format="color"/>
        <attr name="rightBackground" format="reference|color"/>
        <attr name="rightText" format="string"/>
</declare-styleable> </resources>

第二步:創(chuàng)建自定義控件—-創(chuàng)建類CompositControlDemo01,并讓其繼承RelativeLayout

package com.wjc.customwidget_0502;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;


/**
 * Created by admin on 2016/5/2.
 */
public class CompositControlDemo01 extends RelativeLayout {

    //定義與attrs.xml中的自定義屬性對(duì)應(yīng)的屬性
    private int mLeftTextColor;
    private String mLeftText;
    private Drawable mLeftBackground;
    private int mRightTextColor;
    private String mRightText;
    private Drawable mRightBackgound;
    private String mTitle;
    private float mTitleTextSize;
    private int mTitleTextColor;
    //布局參數(shù)
    private LayoutParams mLeftParame;
    private LayoutParams mRightParame;
    private LayoutParams mTitleParame;
    //定義顯示的布局
    private Button mLeftButton;
    private Button mRightButton;
    private TextView mTitleView;
    //定義一個(gè)公共接口
    private topbarClickListener mListener;


    //構(gòu)造函數(shù),attrs就是布局文件傳過(guò)來(lái)的對(duì)應(yīng)的屬性
    public CompositControlDemo01(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
        initView(context);
    }

    //將attrs.xml中定義的屬性值存入typedArray中
    public void initAttrs(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);
        mLeftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, 0);
        mLeftText = ta.getString(R.styleable.TopBar_leftText);
        mLeftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);

        mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
        mRightText = ta.getString(R.styleable.TopBar_rightText);
        mRightBackgound = ta.getDrawable(R.styleable.TopBar_rightBackground);

        mTitle = ta.getString(R.styleable.TopBar_titleText);
        mTitleTextSize = ta.getDimension(R.styleable.TopBar_titleSize, 10);
        mTitleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor2, 0);
        ta.recycle();//避免重新創(chuàng)建時(shí)的錯(cuò)誤
    }

    //組合控件,并將屬性分配給他們,并設(shè)置監(jiān)聽(tīng)事件
    public void initView(Context context) {
        mLeftButton = new Button(context);
        mRightButton = new Button(context);
        mTitleView = new TextView(context);

        mLeftButton.setTextColor(mLeftTextColor);
        mLeftButton.setText(mLeftText);
        mLeftButton.setBackground(mLeftBackground);

        mRightButton.setTextColor(mRightTextColor);
        mRightButton.setText(mRightText);
        mRightButton.setBackground(mRightBackgound);

        mTitleView.setTextColor(mTitleTextColor);
        mTitleView.setText(mTitle);
        mTitleView.setTextSize(mTitleTextSize);
        mTitleView.setGravity(Gravity.CENTER);

        //為元素設(shè)定相應(yīng)的布局參數(shù)
        mLeftParame = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mLeftParame.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
        addView(mLeftButton, mLeftParame);

        mRightParame = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mRightParame.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
        addView(mRightButton, mRightParame);

        mTitleParame = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        mTitleParame.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
        addView(mTitleView, mTitleParame);


        //按鈕的點(diǎn)擊事件,不需要具體的實(shí)現(xiàn)
        //只需調(diào)用者接口的方法,回調(diào)的時(shí)候,會(huì)有具體的實(shí)現(xiàn)
        mLeftButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.leftClick();
            }
        });
        mRightButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mListener.rightClick();
            }
        });
    }

    //定義接口
    //接口對(duì)象,實(shí)現(xiàn)回調(diào)機(jī)制,在回調(diào)方法中,通過(guò)映射的接口對(duì)象調(diào)用接口的方法
    //而不用去考慮如何實(shí)現(xiàn),具體的實(shí)現(xiàn)由調(diào)用者去創(chuàng)建
    public interface topbarClickListener {
        void leftClick();
        void rightClick();
    }

    //暴露一個(gè)方法給調(diào)用者來(lái)注冊(cè)接口回調(diào)
    //通過(guò)接口來(lái)獲取回調(diào)者對(duì)接口方法的實(shí)現(xiàn)
    public void setOnTopbarClickListener(topbarClickListener mListener) {
        this.mListener = mListener;
    }

    /**
     * 設(shè)置按鈕的顯示與否通過(guò)id區(qū)分按鈕,flag區(qū)分是否顯示
     *
     * @param id   id
     * @param flag is Visable?
     */
    public void setButtonVisable(int id, boolean flag) {
        if (flag) {
            if (id == 0) {
                mLeftButton.setVisibility(View.VISIBLE);
            } else {
                mRightButton.setVisibility(View.VISIBLE);
            }
        } else {
            if (id == 0) {
                mLeftButton.setVisibility(View.GONE);
            } else {
                mRightButton.setVisibility(View.GONE);
            }
        }
    }
}

第三步:引用UI模板—?jiǎng)?chuàng)建topbar.xml文件

<?xml version="1.0" encoding="utf-8"?>
   <com.wjc.customwidget_0502.CompositControlDemo01
       xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:custom="http://schemas.android.com/apk/res-auto"
       android:id="@+id/topBar"
       android:layout_width="wrap_content"
       android:layout_height="50dp"
       android:padding="5dp"
      android:background="#3F7EA4"

       custom:leftBackground="@drawable/chevron_left"
       custom:leftTextColor="#ff00"
       custom:leftText="返回"

        custom:rightText="更多"
        custom:rightTextColor="#ff00"
        custom:rightBackground="#ffccff"

        custom:titleText="自定義標(biāo)題"
        custom:titleTextColor2="#555555"
        custom:titleSize="10sp"
       >
</com.wjc.customwidget_0502.CompositControlDemo01>

注:代碼中

xmlns:android=http://schemas.android.com/apk/res/android

表示:引用android系統(tǒng)的屬性,而

xmlns:custom=http://schemas.android.com/apk/res-auto

表示:引用第三方控件的屬性,即引用自定義的屬性

通過(guò)如上的代碼,我們就可以在其他的布局文件中,直接帶調(diào)用標(biāo)簽來(lái)引用這個(gè)UI模板View,代碼如下

<include layout="@layout/topbar"/>

第四步:實(shí)現(xiàn)接口回調(diào)——即寫(xiě)一個(gè)activity引用此布局

package com.wjc.customwidget_0502;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    CompositControlDemo01 mTopbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTopbar=(CompositControlDemo01)findViewById(R.id.topBar);//初始化組合控件
        //為topBar中的按鈕注冊(cè)監(jiān)聽(tīng)事件 
        mTopbar.setOnTopbarClickListener(new CompositControlDemo01.topbarClickListener() {
            @Override
            public void leftClick() {
                Toast.makeText(MainActivity.this, "back", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void rightClick() {
                Toast.makeText(MainActivity.this,"more",Toast.LENGTH_LONG).show();
            }
        });
        /*  //是否顯示相應(yīng)的按鈕
        mTopbar.setButtonVisable(0,true);//只顯示左邊按鈕*/
    }


}

感謝各位的閱讀!關(guān)于“android中自定義View之復(fù)合控件的示例分析”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI