android自訂UI模板圖文詳解

來源:互聯網
上載者:User

標籤:android   xml   ui   布局   自訂ui模板   

不知道大家在實際開發中有沒有自訂過UI模板?今天花時間研究了一下android中自訂UI模板,與大家分享一下。
每個設計良好的App都是自訂標題列,在自訂標題列的過程中大部分人可能都是自訂一個標題的xml檔案,然後在需要的地方直接通過include來引用,這比起在每個布局檔案中寫標題列已經進化很多了,但仍然不是最簡單有效方法,我們為什麼不能自訂一個標題控制項呢?今天就帶大家自己做一個標題列控制項。如下:

開始啦:

第一步:自訂xml屬性

建立一個android項目,在values檔案夾中建立一個atts.xml的檔案,在這個xml檔案中聲明我們一會在使用自訂控制項時候需要指明的屬性。
atts.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <declare-styleable name="ToolBar">        <attr name="title" format="string" />        <attr name="titleTextSize" format="dimension" />        <attr name="titleTextColor" format="color" />        <attr name="leftBackground" format="reference|color" />        <attr name="leftText" format="string" />        <attr name="leftTextColor" format="reference|color" />        <attr name="rightBackground" format="reference|color" />        <attr name="rightText" format="string" />        <attr name="rightTextColor" format="reference|color" />    </declare-styleable></resources>

前面的name是我們要使用的屬性名稱,後面的format表示該屬性接受的值的格式,string表示該屬性的值是一個字串,color表示該屬性的值是一個顏色值,dimension表示該屬性的值是一個尺寸,reference表示該屬性的值可以參考某一個資源id,其他常見的format值還有:boolean(布爾值)、float(浮點值)、integer(整型值)、fraction(百分數)、enum(枚舉值)、flag(位或運算)。

第二步:自訂標題類
在Java檔案中自訂一個類繼承RelativeLayout,並實現它的構造方法,我們的標題列由三部分組成,左右兩邊各是一個Button,中間是一個TextView,因此我們在這個布局檔案中要做的事就是對這三個控制項進行處理。

先聲明標題列的三個空間及相關參數,這些參數都是根據atts.xml中來設定的,因為我們在引用自訂控制項的時候是從xml中引用的,屬性的設定都在xml檔案中,我們從xml檔案中拿到屬性的值後再對控制項設定賦值。

    /**     * 標題列的三個控制項     */    private Button leftBtn, rightBtn;    private TextView title;    /**     * 左邊按鈕的屬性     */    private int leftTextColor;    private Drawable leftBackground;    private String leftText;    /**     * 右邊按鈕的屬性     */    private int rightTextColor;    private Drawable rightBackground;    private String rightText;    /**     * 中間TextView的屬性     */    private int titleTextColor;    private String titleText;    private float titleTextSize;    /**     * 三個控制項的布局參數     */    private LayoutParams leftParams, rightParams, titleParams;

下面是構造方法,構造方法傳入兩個參數,一個是上下文參數,另外一個是AttributeSet,AttributeSet是一個屬性的集合,用它可以處理一組xml標籤集合。使用ta.getXXX方法,我們可以先從xml檔案獲得屬性的值,然後把這些值設定給控制項。最後通過LayoutParams來設定控制項的寬高,設定好寬高之後,調用addView方法,添加控制項。

    public MyToolBar(Context context, AttributeSet attrs) {        super(context, attrs);        TypedArray ta = context.obtainStyledAttributes(attrs,                R.styleable.ToolBar);        leftTextColor = ta.getColor(R.styleable.ToolBar_leftTextColor, 0);        leftBackground = ta.getDrawable(R.styleable.ToolBar_leftBackground);        leftText = ta.getString(R.styleable.ToolBar_leftText);        rightTextColor = ta.getColor(R.styleable.ToolBar_rightTextColor, 0);        rightBackground = ta.getDrawable(R.styleable.ToolBar_rightBackground);        rightText = ta.getString(R.styleable.ToolBar_rightText);        titleText = ta.getString(R.styleable.ToolBar_title);        titleTextColor = ta.getColor(R.styleable.ToolBar_titleTextColor, 0);        titleTextSize = ta.getDimension(R.styleable.ToolBar_titleTextSize, 0);        //對ta進行回收        ta.recycle();        leftBtn = new Button(context);        rightBtn = new Button(context);        title = new TextView(context);        /**         * 設定屬性         */        leftBtn.setText(leftText);        leftBtn.setTextColor(leftTextColor);        leftBtn.setBackground(leftBackground);        rightBtn.setText(rightText);        rightBtn.setTextColor(rightTextColor);        rightBtn.setBackground(rightBackground);        title.setText(titleText);        title.setTextColor(titleTextColor);        title.setTextSize(titleTextSize);        title.setGravity(Gravity.CENTER);        //設定整體背景顏色        setBackgroundColor(0x7CFC0055);        leftParams = new LayoutParams(                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,                android.view.ViewGroup.LayoutParams.WRAP_CONTENT);        leftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);        //添加控制項        addView(leftBtn, leftParams);        rightParams = new LayoutParams(                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,                android.view.ViewGroup.LayoutParams.WRAP_CONTENT);        rightParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);        addView(rightBtn, rightParams);        titleParams = new LayoutParams(                android.view.ViewGroup.LayoutParams.WRAP_CONTENT,                android.view.ViewGroup.LayoutParams.MATCH_PARENT);        titleParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);        addView(title, titleParams);    }

第三步:引用我們定義的控制項
自訂好控制項之後,我們就可以使用自訂的控制項了,在主布局的xml檔案中引用我們自訂的控制項。自訂控制項的前三個屬性都是以android:開頭,這表示這些屬性都是系統的,後面的屬性以custombar開頭,表示這些屬性都是我們自訂的,為了能夠使用自訂的custombar,我們需要在RelativeLayout中添加一句:

xmlns:custombar="http://schemas.android.com/apk/res/com.example.mytoolbar"

注意後面的com.example.mytoolbar是你應用的包名稱。如果閣下使用的不是eclipse而是android studio,那麼這一行不用這麼麻煩,只需要寫上:

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

我們自訂的屬性就是我們在atts.xml中聲明的要設定的屬性。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:custombar="http://schemas.android.com/apk/res/com.example.mytoolbar"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent" >    <com.example.mytoolbar.MyToolBar        android:id="@+id/mytoolbar"        android:layout_width="match_parent"        android:layout_height="48dp"        custombar:leftBackground="@android:color/holo_blue_light"        custombar:leftText="返回"        custombar:leftTextColor="@android:color/black"        custombar:rightBackground="@android:color/holo_blue_light"        custombar:rightText="更多"        custombar:rightTextColor="@android:color/black"        custombar:title="標題列"        custombar:titleTextColor="@android:color/black"        custombar:titleTextSize="18sp" >    </com.example.mytoolbar.MyToolBar></RelativeLayout>

做完這些工作之後,運行你的項目,就能看到我們在文章開頭給出的那個畫面了。

第四步:為自訂控制項添加事件

好像還少點什麼,是的,我們的控制項都還沒有點擊事件。要給事件設定點擊事件,需要先在自訂控制項中聲明一個事件介面,並聲明一個介面的執行個體:

private OnToolBarClickListener listener;    public interface OnToolBarClickListener {        /**         * 左邊按鈕點擊事件         */        public void leftClick();        /**         * 右邊按鈕點擊事件         */        public void rightClick();    }

然後暴露出來一個方法給其他類調用,這個方法的參數就是這個介面:

    public void setOnToolBarClickListener(OnToolBarClickListener listener) {        this.listener = listener;    }

最後在左右兩個按鈕的點擊事件中調用介面中的方法即可,聰明的看官猜猜這是什麼模式?

        leftBtn.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                listener.leftClick();            }        });        rightBtn.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                listener.rightClick();            }        });

方法寫好了,我們在MainActivity中調用看看:

public class MainActivity extends Activity {    private MyToolBar toolBar;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        getActionBar().hide();        this.toolBar = (MyToolBar) this.findViewById(R.id.mytoolbar);        toolBar.setOnToolBarClickListener(new OnToolBarClickListener() {            @Override            public void rightClick() {                Toast.makeText(MainActivity.this,"右邊點擊", Toast.LENGTH_LONG).show();            }            @Override            public void leftClick() {                Toast.makeText(MainActivity.this,"左邊點擊", Toast.LENGTH_LONG).show();            }        });    }}

這段代碼相信大家都能看懂:
我們直接看吧:

關於android自訂UI模板就給大家介紹到這裡,有問題請留言。本項目完整代碼下載。

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。若有錯誤地方,還望批評指正,不勝感激。

android自訂UI模板圖文詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.