android 組合方式自訂控制項

來源:互聯網
上載者:User

標籤:

          實現了《android 群英傳》的TopBar的小執行個體。如下:

記錄下來,方便下次查看。主要的原理是將2個Button和一個TextView組合在一個RelativeLayout之中。

代碼如下。首先定義自訂屬性attrs.xml,也可能是先實現一個控制項,然後再抽象出一些屬性。

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

然後是自定一個一個TopBar,在之中組合Button和TextView,動態地設定屬性值和布局。下面是自訂的按鈕點擊事件的介面。

package com.example.androidviewlearn;public interface TopBarClickListener {        void leftClick();    void rightClick();}
View Code

 

package com.example.androidviewlearn;import android.annotation.SuppressLint;import android.content.Context;import android.content.res.TypedArray;import android.graphics.drawable.Drawable;import android.os.Trace;import android.util.AttributeSet;import android.view.Gravity;import android.view.View;import android.widget.Button;import android.widget.RelativeLayout;import android.widget.TextView;public class TopBar extends RelativeLayout {    // 擷取自訂的類型數組s    private TypedArray ta;    private int mLeftTextColor;    private Drawable mLeftBackground;    private String mLeftText;    private int mRightTextColor;    private Drawable mRightBackground;    private String mRightText;    private int mTitleTextSize;    private int mTitleTextColor;    private String mTtile;    private Button mLeftButton;    private Button mRightButton;    private TextView mTitleView;    private LayoutParams mLeftLayoutParams;    private LayoutParams mRightLayoutParams;    private LayoutParams mTitleLayoutParams;    private TopBarClickListener mBarClickListener;    //三個建構函式,一般採用這些寫法。    public TopBar(Context context) {        this(context, null);        // TODO Auto-generated constructor stub    }    public TopBar(Context context, AttributeSet attrs) {        this(context, attrs, 0);        // TODO Auto-generated constructor stub    }    @SuppressLint("NewApi")    public TopBar(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        // TODO Auto-generated constructor stub        //擷取布局中設定的自訂屬性        getStyleValue(context, attrs);        //初始化控制項,並且把屬性值設定進去        initView(context);        //設定各個控制項的布局        setLayout();    }    /**     * 設定自訂空間的布局屬性     */    private void setLayout() {        mLeftLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);        mLeftLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);        addView(mLeftButton, mLeftLayoutParams);        mRightLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);        mRightLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);        addView(mRightButton, mRightLayoutParams);        mTitleLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);        mTitleLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);        addView(mTitleView, mTitleLayoutParams);    }    @SuppressLint("NewApi")    /**     * 初始化控制項,並且給空間賦予屬性和事件     * @param context     */    private 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);        mLeftButton.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View paramView) {                // TODO Auto-generated method stub                mBarClickListener.leftClick();            }        });        mRightButton.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View paramView) {                // TODO Auto-generated method stub                mBarClickListener.rightClick();            }        });        mRightButton.setTextColor(mRightTextColor);        mRightButton.setText(mRightText);        mRightButton.setBackground(mRightBackground);        mTitleView.setText(mTtile);        mTitleView.setTextColor(mTitleTextColor);        mTitleView.setTextSize(mTitleTextSize);        mTitleView.setGravity(Gravity.CENTER);    }    /**     * 擷取自訂空間上的style     * @param context     * @param attrs     */    private void getStyleValue(Context context, AttributeSet attrs) {        ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);        mLeftTextColor = ta.getColor(R.styleable.TopBar_leftTextColor, 0);        mLeftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);        mLeftText = ta.getString(R.styleable.TopBar_leftText);        mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);        mRightBackground = ta.getDrawable(R.styleable.TopBar_rightBackground);        mRightText = ta.getString(R.styleable.TopBar_rightText);        mTitleTextSize = ta.getDimensionPixelSize(R.styleable.TopBar_titleTextSize, 10);        mTitleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, 0);        mTtile = ta.getString(R.styleable.TopBar_title);        ta.recycle();    }    public TopBarClickListener getmBarClickListener() {        return mBarClickListener;    }    public void setBarClickListener(TopBarClickListener mBarClickListener) {        this.mBarClickListener = mBarClickListener;    }    /**     * id=1標識→_→,id-0標識左邊     *      * @param id     * @param flag     */    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);            }        }    }}
View Code

之後定義一個layout,activity_main.xml,把放入自訂布局和設定參數。

<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"    tools:context="com.example.androidviewlearn.MainActivity" >        <com.example.androidviewlearn.TopBar        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="match_parent"        android:layout_height="40dp"                      custom:leftBackground="#98F5FF"            custom:leftText="Back"           custom:leftTextColor="#FFFAFA"                      custom:rightBackground="#98F5FF"            custom:rightText="More"           custom:rightTextColor="#FFFAFA"                      custom:title="Fuck Day"           custom:titleTextColor="#123412"           custom:titleTextSize="16sp"                    >            </com.example.androidviewlearn.TopBar>    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></LinearLayout>
View Code

特別注意這一行,xmlns:custom="http://schemas.android.com/apk/res-auto"。custom就表示了設定屬性時候的首碼:custom:rightBackground

最後的就是Activity的實現了。

package com.example.androidviewlearn;import android.app.Activity;import android.os.Bundle;import android.view.Menu;import android.view.MenuItem;import android.widget.Toast;public class MainActivity extends Activity {    private TopBar mTopBar;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTopBar = (TopBar) findViewById(R.id.topBar);        mTopBar.setBarClickListener(new TopBarClickListener() {                    @Override            public void rightClick() {                // TODO Auto-generated method stub                Toast.makeText(getApplicationContext(), "right fuck button", Toast.LENGTH_LONG).show();                        }                    @Override            public void leftClick() {                // TODO Auto-generated method stub                Toast.makeText(getApplicationContext(), "left fuck button", Toast.LENGTH_LONG).show();            }        });    }}
View Code

 

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.