Android中自訂群組合控制項

來源:互聯網
上載者:User

標籤:

Android中自訂控制項的情況非常多,一般自訂控制項可以分為兩種:繼承控制項及群組控制項。前者是通過繼承View或其子類,重寫方法實現自訂的顯示及事件處理方式;後者是通過組合已有的控制項,來實現結構的簡化和代碼的重用。

本篇文章主要介紹自訂群組合控制項,繼承控制項後續有機會再述。

自訂群組合控制項一般來說都是以ViewGroup及其子類(LinearLayout、RelativeLayout、FrameLayout等)為主,內部嵌套其他控制項,來組合成一個新的控制項,實現一些特定的需要,可以是代碼簡化,結構清晰,重用性較高。

通常來說,我們會實現定義好一個Layout.xml檔案,然後讓我們的自訂控制項去載入此xml,並擷取子控制項,然後設定屬性(可以通過代碼,也可以從資源檔中載入)、添加事件。

自訂要點:

1.載入xml檔案是在構造方法中完成的,通過調用inflate(R.layout.my_layout,this,true),注意第二個和第三個參數;

2.如果需要從資源檔中載入自訂的屬性,則必須重寫Constructor(Context context, AttributeSet attrs)此構造方法,屬性是定義在attrs.xml中的;

3.擷取子控制項對象,可以在構造方法中擷取,也可以重寫onFinishInflate()方法來擷取,個人建議採用第二種,可以保證控制項已經完全載入好了;

4.添加事件可以直接在控制項中寫,不過考慮到擴充性及複用性,建議對外暴露介面。

範例程式碼(代碼比較簡單,只是描述一下思路)

自訂控制項layout:header.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="wrap_content">    <ImageButton android:id="@+id/ib_header"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_centerVertical="true"        android:src="@android:drawable/ic_menu_zoom" />    <TextView android:id="@+id/tv_header"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true" /></RelativeLayout>

自訂控制項類:Header.java

package com.ivan.app1.widgets;import com.ivan.app1.R;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Color;import android.text.TextUtils;import android.util.AttributeSet;import android.view.LayoutInflater;import android.widget.ImageButton;import android.widget.LinearLayout;import android.widget.TextView;/** * 自訂標題列群組控制項,內部包含一個TextView和一個ImageButton * User: xyh * Date: 2015/6/2 * Time: 9:39 */public class Header extends RelativeLayout {    private TextView mTextView;    private ImageButton mImageButton;    private String titleText;    private int titleTextColor;    private float titleTextSize;    public Header(Context context) {        super(context);    }    public Header(Context context, AttributeSet attrs) {        super(context, attrs);        //載入視圖的布局        LayoutInflater.from(context).inflate(R.layout.header,this,true);        //載入自訂的屬性        TypedArray a=context.obtainStyledAttributes(attrs,R.styleable.Header);        titleText=a.getString(R.styleable.Header_titleText);        titleTextColor=a.getColor(R.styleable.Header_titleTextColor, Color.WHITE);        titleTextSize=a.getDimension(R.styleable.Header_titleTextSize,20f);        //回收資源,這一句必須調用        a.recycle();    }    /**     * 此方法會在所有的控制項都從xml檔案中載入完成後調用     */    @Override    protected void onFinishInflate() {        super.onFinishInflate();        //擷取子控制項        mTextView= (TextView) findViewById(R.id.tv_header);        mImageButton= (ImageButton) findViewById(R.id.ib_header);        //將從資源檔中載入的屬性設定給子控制項        if (!TextUtils.isEmpty(titleText))            setPageTitleText(titleText);        setPageTitleTextColor(titleTextColor);        setPageTitleTextSize(titleTextSize);    }    /**     * 設定標題文字     * @param text     */    public void setPageTitleText(String text) {        mTextView.setText(text);    }    /**     * 設定標題文字顏色     * @param color     */    public void setPageTitleTextColor(int color) {        mTextView.setTextColor(color);    }    /**     * 設定標題文字大小     * @param size     */    public void setPageTitleTextSize(float size) {        mTextView.setTextSize(size);    }    /**     * 設定按鈕點擊事件監聽器     * @param listener     */    public void setOnHeaderClickListener(OnClickListener listener) {        mImageButton.setOnClickListener(listener);    }}

自訂屬性檔案:attrs.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <!-- 自訂的屬性-->    <declare-styleable name="Header">        <attr name="titleTextSize" format="dimension" />        <attr name="titleTextColor" format="color" />        <attr name="titleText" format="string"/>    </declare-styleable></resources>

以下是引用方式,activity布局檔案:main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent">    <!-- 注意需要加上命名空間 在eclipse開發工具中:使用 xmlns:app="http://schemas.android.com/apk/res/com.ivan.app1.widgets"         在IntelliJ Idea或者Android Studio中以Gradle構建時,使用 xmlns:app="http://schemas.android.com/apk/res-auto"    -->    <!-- 通過包的類的全名來引用自訂視圖-->    <com.ivan.app1.widgets.Header        android:id="@+id/header"        android:layout_width="match_parent"        android:layout_height="48dp"        android:background="@color/black"        app:titleText="我是標題"        app:titleTextColor="#ff0000"        app:titleTextSize="12sp"/>    <TextView android:layout_width="match_parent"        android:layout_height="match_parent"        android:gravity="center"        android:text="我是內容"        android:textSize="60sp"/></LinearLayout>

 

 主Activity類:MainActivity.java

package com.ivan.app1;import com.ivan.app1.widgets.Header;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Toast;/** * User: xyh * Date: 2015/6/2 * Time: 10:30 */public class MainActivity extends AppCompatActivity {    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        ((Header)findViewById(R.id.header)).setOnHeaderClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Toast.makeText(getApplicationContext(),"標題列的按鈕被點擊了",Toast.LENGTH_LONG).show();            }        });    }}

運行結果:

原創文章,轉載請註明出處。

Android中自訂群組合控制項

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.