Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android應用開發--------------看RadioGroup源碼,寫類似單選選項卡的集成控件(如底部導航,tab等等)

android應用開發--------------看RadioGroup源碼,寫類似單選選項卡的集成控件(如底部導航,tab等等)

編輯:關於Android編程

 

 

data-cke-saved-src=https://www.android5.online/Android/UploadFiles_5356/201702/2017022314160044.png

上面就是需求設計,4個類似的布局控件,每次只能選擇一個,然後得到上面對應的錢數。(上面只是效果圖,實際數據是從服務器獲取,然後付到控件上)

看到這種,我們就回想到,幾種實現方法。

1.把這個整體寫一個布局,在xml布局中,復制粘貼,代碼,湊夠4個。非常不建議這樣,因為4個的布局樣式是一樣的,只是數據可能不相同,所以我們應該寫一個組合控件然後重復利用。

2.就是寫一個data-cke-saved-src=https://www.android5.online/Android/UploadFiles_5356/201702/2017022314160027.png單個的布局控件,然後設置一些設置數據的方法,然後重復利用它。引入四個控件。這樣在一定程度上達到了代碼重復利用性,但是以後在布局中這一塊要是去掉,可能你要修改的代碼也是會比較多了。

 

3.還有一種就是使用GridView,我們看多多個相同的布局,就會相到使用listView和GridView。這種方法是可以使用的,不過在有個問題是,如果沒有數據的前提下,它將會是一個空布局,不太好看,對於後期修改或去掉這一部分布局的話,相對來說好算比較好修改,去電一個GridView和他相對應的adapter就好了。

 

下面我們在針對第二種來說一下,解決一下他的不好修改的特點,因為,我們一般寫完程序之後就會懶得修改,所以我們在第一次編寫的時候,要為以後的修改做好准備,一切為了方便修改。因為程序員都知道,產品的需求是一直在變化,。。。。。你們懂就好,假如,產品想把這個東西換一個樣式,或是直接其用掉這一部分布局,那我們就盡量做到,刪除幾行代碼搞定它。那麼就需要我們在2方式的基礎上再封裝一層。

把四個弄成一個控件,然後再整體加進去。

 

你們仔細看,上面的是不是一個單選按鈕組?就和androd的radiobutton控件相似,然後用一個radioGroup包含。

所以我們可以針對這個寫一個類似RadioGroup和RadioButton那樣類似的東西。

 

首先先解決RadioButton類似的控件,先寫一個布局,data-cke-saved-src=https://www.android5.online/Android/UploadFiles_5356/201702/2017022314160027.png這樣的布局。

 

布局為,



    

        

            

            
        

        
    

    


就這麼簡單寫一下。

然後把其整體封裝為一個組合控件,編寫方法什麼的。

 

public class RechargeValueLayout extends FrameLayout{

	private View view;
	private TextView mZengs;
	private TextView mMoney;
	private TextView mCords;
	private String money;
	private LinearLayout mllbg;

	private Boolean isChecked;
	
	public RechargeValueLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public RechargeValueLayout(Context context, AttributeSet attrs) {
		super(context, attrs);
		view = View.inflate(context, R.layout.recharge_value_item, this);
		mllbg = (LinearLayout)view.findViewById(R.id.llbg);
		mZengs = (TextView)view.findViewById(R.id.tvZengs);
		mMoney = (TextView)view.findViewById(R.id.tvMoney);
		mCords = (TextView)view.findViewById(R.id.tvcords);
	}

	public RechargeValueLayout(Context context) {
		super(context);
	}
	
	public void setChecked(Boolean isChecked){
		Log.i(TAG2, isSelected===>>>>+isChecked);
		if(isChecked==this.isChecked){
			return;
		}
		if(isChecked){
			mllbg.setBackgroundResource(R.drawable.btn_recharge_active);
		}else{
			mllbg.setBackgroundResource(R.drawable.btn_recharge);
		}
		this.isChecked = isChecked;
	}
	
	public boolean isChecked(){
		return this.isChecked;
	}
	
	public void setZengsValue(int value){
		if(value>0){
			mZengs.setVisibility(View.VISIBLE);
			mZengs.setText(送+value+);
		}else{
			mZengs.setVisibility(View.GONE);
		}
	}
	public String getMoneyValue(){
		return this.money;
	}
	public void setMoneyValue(int value){
		if(value>0){
			mMoney.setText(value+);
			this.money = value+;
		}else{
			mMoney.setText(0幣);
		}
	}
	
	public void setCordsValue(int value){
		if(value>0){
			mCords.setText(value+幣);
		}else{
			mCords.setText(0幣);
		}
	}
	
	
}

這樣,你就直接可以引用其路徑,直接使用這個組合控件。其實到這裡,就實現了2方式所說的。但是僅用這個,那麼我們只是實現了布局重用,但是不好進行替換修改,你可以想想,這麼一個控件裡有3個textView,並且我們要對其textView進行賦值,也就是說我們要對12TextView經行操作,如果這12TextView放在我們activity裡,一是代碼過於臃腫,二是你想想,如果以後去掉的話,我們就得對這所有涉及到這12個TextView的代碼都得進行刪除。

所以我們現在要把這四個控件再給他們一個類似RadioGroup的容器,在RadioGroup裡有一個點擊事件,只要對RadioCroup設置上監聽,那麼在RadioGroup的控件就自動設置上了監聽,所以,咱activity裡面我們只需要這個RadioGroup的控件代碼,1個對12個,你們想想到知道後續修改操作那種方便。

 

開始是想的定義的布局控件,這個布局控件得到自己裡面的孩子數,然後再遍歷循環給孩子設置上監聽,可是失敗了。

具體的說說失敗的代碼。

  

            
            

            
            

            
            
            
        


這是布局,首先把RechargeValueLayout放到RechargeValueGroup裡面,然後RechargeValueGroup裡面得到自己的孩子數,

public class RechargeValueGroup extends FrameLayout {

	private OnItemTabClickListener listener;
	
	public RechargeValueGroup(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}

	public RechargeValueGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	
	public RechargeValueGroup(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}
	
	private void init() {
		int count = getChildCount();
		for (int i = 0; i < count; i++) {
			getChildAt(i).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(listener!=null){
						listener.onItemClick(RechargeValueGroup.this,v.getId());
					}
				}
			});
		}
	}

	/**
	 * 定義Group的監聽,點擊每一個子按鈕就會返回相對應子按鈕的信息,以方便操作
	 */
	public interface OnItemTabClickListener {
		public void onItemClick(RechargeValueGroup view, int checkedId);
	}
	
}


可是這樣有個問題,在構造函數執行的時候是獲得不到孩子數的,這樣就沒法給孩子設置上監聽了。

然後我就想記得以前是在onMeasure裡面可以得到孩子數,把init的部分放到onMeasure或onLayout方法裡,孩子數是得到了,可是這兩個方法是,只要布局有變化,其都會走一遍,也就是說只要你布局有變化,他們就會執行,所以出現了一些問題,所以在這兩個方法中設置監聽是不太好的。

那怎麼樣技能自動獲得孩子數,又能給對應的孩子設置上監聽呢?

 

於是我就去看了一下RadioGroup的源碼。

/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.widget;

import com.android.internal.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;


/**
 * 

This class is used to create a multiple-exclusion scope for a set of radio * buttons. Checking one radio button that belongs to a radio group unchecks * any previously checked radio button within the same group.

* *

Intially, all of the radio buttons are unchecked. While it is not possible * to uncheck a particular radio button, the radio group can be cleared to * remove the checked state.

* *

The selection is identified by the unique id of the radio button as defined * in the XML layout file.

* *

XML Attributes

*

See {@link android.R.styleable#RadioGroup RadioGroup Attributes}, * {@link android.R.styleable#LinearLayout LinearLayout Attributes}, * {@link android.R.styleable#ViewGroup ViewGroup Attributes}, * {@link android.R.styleable#View View Attributes}

*

Also see * {@link android.widget.LinearLayout.LayoutParams LinearLayout.LayoutParams} * for layout attributes.

* * @see RadioButton * */ public class RadioGroup extends LinearLayout { // holds the checked id; the selection is empty by default private int mCheckedId = -1; // tracks children radio buttons checked state private CompoundButton.OnCheckedChangeListener mChildOnCheckedChangeListener; // when true, mOnCheckedChangeListener discards events private boolean mProtectFromCheckedChange = false; private OnCheckedChangeListener mOnCheckedChangeListener; private PassThroughHierarchyChangeListener mPassThroughListener; /** * {@inheritDoc} */ public RadioGroup(Context context) { super(context); setOrientation(VERTICAL); init(); } /** * {@inheritDoc} */ public RadioGroup(Context context, AttributeSet attrs) { super(context, attrs); // retrieve selected radio button as requested by the user in the // XML layout file TypedArray attributes = context.obtainStyledAttributes( attrs, com.android.internal.R.styleable.RadioGroup, com.android.internal.R.attr.radioButtonStyle, 0); int value = attributes.getResourceId(R.styleable.RadioGroup_checkedButton, View.NO_ID); if (value != View.NO_ID) { mCheckedId = value; } final int index = attributes.getInt(com.android.internal.R.styleable.RadioGroup_orientation, VERTICAL); setOrientation(index); attributes.recycle(); init(); } private void init() { mChildOnCheckedChangeListener = new CheckedStateTracker(); mPassThroughListener = new PassThroughHierarchyChangeListener(); super.setOnHierarchyChangeListener(mPassThroughListener); } /** * {@inheritDoc} */ @Override public void setOnHierarchyChangeListener(OnHierarchyChangeListener listener) { // the user listener is delegated to our pass-through listener mPassThroughListener.mOnHierarchyChangeListener = listener; } /** * {@inheritDoc} */ @Override protected void onFinishInflate() { super.onFinishInflate(); // checks the appropriate radio button as requested in the XML file if (mCheckedId != -1) { mProtectFromCheckedChange = true; setCheckedStateForView(mCheckedId, true); mProtectFromCheckedChange = false; setCheckedId(mCheckedId); } } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if (child instanceof RadioButton) { final RadioButton button = (RadioButton) child; if (button.isChecked()) { mProtectFromCheckedChange = true; if (mCheckedId != -1) { setCheckedStateForView(mCheckedId, false); } mProtectFromCheckedChange = false; setCheckedId(button.getId()); } } super.addView(child, index, params); } /** *

Sets the selection to the radio button whose identifier is passed in * parameter. Using -1 as the selection identifier clears the selection; * such an operation is equivalent to invoking {@link #clearCheck()}.

* * @param id the unique id of the radio button to select in this group * * @see #getCheckedRadioButtonId() * @see #clearCheck() */ public void check(int id) { // don't even bother if (id != -1 && (id == mCheckedId)) { return; } if (mCheckedId != -1) { setCheckedStateForView(mCheckedId, false); } if (id != -1) { setCheckedStateForView(id, true); } setCheckedId(id); } private void setCheckedId(int id) { mCheckedId = id; if (mOnCheckedChangeListener != null) { mOnCheckedChangeListener.onCheckedChanged(this, mCheckedId); } } private void setCheckedStateForView(int viewId, boolean checked) { View checkedView = findViewById(viewId); if (checkedView != null && checkedView instanceof RadioButton) { ((RadioButton) checkedView).setChecked(checked); } } /** *

Returns the identifier of the selected radio button in this group. * Upon empty selection, the returned value is -1.

* * @return the unique id of the selected radio button in this group * * @see #check(int) * @see #clearCheck() * * @attr ref android.R.styleable#RadioGroup_checkedButton */ public int getCheckedRadioButtonId() { return mCheckedId; } /** *

Clears the selection. When the selection is cleared, no radio button * in this group is selected and {@link #getCheckedRadioButtonId()} returns * null.

* * @see #check(int) * @see #getCheckedRadioButtonId() */ public void clearCheck() { check(-1); } /** *

Register a callback to be invoked when the checked radio button * changes in this group.

* * @param listener the callback to call on checked state change */ public void setOnCheckedChangeListener(OnCheckedChangeListener listener) { mOnCheckedChangeListener = listener; } /** * {@inheritDoc} */ @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new RadioGroup.LayoutParams(getContext(), attrs); } /** * {@inheritDoc} */ @Override protected boolean checkLayoutParams(ViewGroup.LayoutParams p) { return p instanceof RadioGroup.LayoutParams; } @Override protected LinearLayout.LayoutParams generateDefaultLayoutParams() { return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); } @Override public void onInitializeAccessibilityEvent(AccessibilityEvent event) { super.onInitializeAccessibilityEvent(event); event.setClassName(RadioGroup.class.getName()); } @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); info.setClassName(RadioGroup.class.getName()); } /** *

This set of layout parameters defaults the width and the height of * the children to {@link #WRAP_CONTENT} when they are not specified in the * XML file. Otherwise, this class ussed the value read from the XML file.

* *

See * {@link android.R.styleable#LinearLayout_Layout LinearLayout Attributes} * for a list of all child view attributes that this class supports.

* */ public static class LayoutParams extends LinearLayout.LayoutParams { /** * {@inheritDoc} */ public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); } /** * {@inheritDoc} */ public LayoutParams(int w, int h) { super(w, h); } /** * {@inheritDoc} */ public LayoutParams(int w, int h, float initWeight) { super(w, h, initWeight); } /** * {@inheritDoc} */ public LayoutParams(ViewGroup.LayoutParams p) { super(p); } /** * {@inheritDoc} */ public LayoutParams(MarginLayoutParams source) { super(source); } /** *

Fixes the child's width to * {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} and the child's * height to {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} * when not specified in the XML file.

* * @param a the styled attributes set * @param widthAttr the width attribute to fetch * @param heightAttr the height attribute to fetch */ @Override protected void setBaseAttributes(TypedArray a, int widthAttr, int heightAttr) { if (a.hasValue(widthAttr)) { width = a.getLayoutDimension(widthAttr, layout_width); } else { width = WRAP_CONTENT; } if (a.hasValue(heightAttr)) { height = a.getLayoutDimension(heightAttr, layout_height); } else { height = WRAP_CONTENT; } } } /** *

Interface definition for a callback to be invoked when the checked * radio button changed in this group.

*/ public interface OnCheckedChangeListener { /** *

Called when the checked radio button has changed. When the * selection is cleared, checkedId is -1.

* * @param group the group in which the checked radio button has changed * @param checkedId the unique identifier of the newly checked radio button */ public void onCheckedChanged(RadioGroup group, int checkedId); } private class CheckedStateTracker implements CompoundButton.OnCheckedChangeListener { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { // prevents from infinite recursion if (mProtectFromCheckedChange) { return; } mProtectFromCheckedChange = true; if (mCheckedId != -1) { setCheckedStateForView(mCheckedId, false); } mProtectFromCheckedChange = false; int id = buttonView.getId(); setCheckedId(id); } } /** *

A pass-through listener acts upon the events and dispatches them * to another listener. This allows the table layout to set its own internal * hierarchy change listener without preventing the user to setup his.

*/ private class PassThroughHierarchyChangeListener implements ViewGroup.OnHierarchyChangeListener { private ViewGroup.OnHierarchyChangeListener mOnHierarchyChangeListener; /** * {@inheritDoc} */ public void onChildViewAdded(View parent, View child) { if (parent == RadioGroup.this && child instanceof RadioButton) { int id = child.getId(); // generates an id if it's missing if (id == View.NO_ID) { id = View.generateViewId(); child.setId(id); } ((RadioButton) child).setOnCheckedChangeWidgetListener( mChildOnCheckedChangeListener); } if (mOnHierarchyChangeListener != null) { mOnHierarchyChangeListener.onChildViewAdded(parent, child); } } /** * {@inheritDoc} */ public void onChildViewRemoved(View parent, View child) { if (parent == RadioGroup.this && child instanceof RadioButton) { ((RadioButton) child).setOnCheckedChangeWidgetListener(null); } if (mOnHierarchyChangeListener != null) { mOnHierarchyChangeListener.onChildViewRemoved(parent, child); } } } }

 

這就是RadioGroup的源碼,加上注釋什麼的一共400來行代碼,所以不是很多,然後就開始看源碼。其中一開始在init()中,有這麼一個監聽,

mPassThroughListener = new PassThroughHierarchyChangeListener();
        super.setOnHierarchyChangeListener(mPassThroughListener);

然後找到其對應的監聽,

 private class PassThroughHierarchyChangeListener implements
            ViewGroup.OnHierarchyChangeListener {
        private ViewGroup.OnHierarchyChangeListener mOnHierarchyChangeListener;

        /**
         * {@inheritDoc}
         */
        public void onChildViewAdded(View parent, View child) {
            if (parent == RadioGroup.this && child instanceof RadioButton) {
                int id = child.getId();
                // generates an id if it's missing
                if (id == View.NO_ID) {
                    id = View.generateViewId();
                    child.setId(id);
                }
                ((RadioButton) child).setOnCheckedChangeWidgetListener(
                        mChildOnCheckedChangeListener);
            }

            if (mOnHierarchyChangeListener != null) {
                mOnHierarchyChangeListener.onChildViewAdded(parent, child);
            }
        }

        /**
         * {@inheritDoc}
         */
        public void onChildViewRemoved(View parent, View child) {
            if (parent == RadioGroup.this && child instanceof RadioButton) {
                ((RadioButton) child).setOnCheckedChangeWidgetListener(null);
            }

            if (mOnHierarchyChangeListener != null) {
                mOnHierarchyChangeListener.onChildViewRemoved(parent, child);
            }
        }
    }


這個監聽繼承了ViewGroup.OnHierarchyChangeListener接口,你通過查資料你就會發現,這個監聽接口是對其 層次結構的監聽,不像
onMeasure或onLayout,他只有在層次結構發生變化時,也就是說在添加view和移除view的時候才會調用,所以他有兩個回調方法。onChildViewAdded和onChildViewRemoved。在初始化的時候,子布局是一個一個的被添加到RadioGroup,所以調用onChildViewAdded,可以得帶其對應的孩子,就可以對其設置監聽了。

這樣設置就不會出現重復執行等問題。

 

然後這一步解決了就好說了。下一把就是我們觸發監聽後,要這幾個控件協調控制,因為只有一個是能被選中。所以在監聽的時候我們應該去改變子控件的狀態等。

這一步就不細說了,應該都會順著理清楚,就是只保持一個被選中就可以。附上代碼,就是根據需求稍微改動了一下RadioGroup

 

public class RechargeValueGroup extends LinearLayout {

	private ArrayList tabChildsId = new ArrayList();

	private OnItemTabClickListener listener;
	private PassThroughHierarchyChangeListener mPassThroughListener;
	private CheckedStateTracker mChildOnCheckedChangeListener;

	/**
	 * 記錄當前id,默認id為-1
	 */
	private int mCheckedId = -1;

	public RechargeValueGroup(Context context, AttributeSet attrs,
			int defStyle) {
		super(context, attrs, defStyle);
	}

	public RechargeValueGroup(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public RechargeValueGroup(Context context) {
		super(context);
	}

	private void init() {
		// radiobutton的監聽
		mChildOnCheckedChangeListener = new CheckedStateTracker();

		// 層次結構的監聽
		mPassThroughListener = new PassThroughHierarchyChangeListener();
		// 設置監聽
		super.setOnHierarchyChangeListener(mPassThroughListener);
	}

	/**
	 * 設置tab數據
	 * 
	 * @param datas
	 */
	public void setDataOfTabs(List datas) {
		Log.i(TAG2,getChildCount()===>>>+getChildCount());
		Log.i(TAG2,datas()===>>>+datas.size());
		int count = 0;
		if (datas.size() >= getChildCount()) {
			count = getChildCount();
//			return;
		}else{
			count = datas.size();
		}
		for (int i = 0; i < count; i++) {
			Log.i(TAG2,data=1111==>>>);
			RechargeValueLayout view = (RechargeValueLayout) findViewById(tabChildsId.get(i));
			RechargeNumInfo data = datas.get(i);
			Log.i(TAG2,data===>>>+data);
			view.setMoneyValue(data.chargeNum);
			view.setCordsValue(data.gzyNum);
			view.setZengsValue(data.giftNum);
		}

	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void onFinishInflate() {
		super.onFinishInflate();
		Log.i(TAG2, onFinishInflate=111==>>>>);
		check(mCheckedId);
	}

	/**
	 * 改變item的選擇狀態
	 * 
	 * @param viewId
	 * @param checked
	 *            true 為選擇,false 為不選擇
	 */
	private void setCheckedStateForView(int viewId, boolean checked) {
		Log.i(TAG2, setCheckedStateForView====>>>);
		View checkedView = findViewById(viewId);
		Log.i(TAG2, setCheckedStateForView===checkedView=>>> + checkedView);
		if (checkedView != null && checkedView instanceof RechargeValueLayout) {
			((RechargeValueLayout) checkedView).setChecked(checked);
			Log.i(TAG2, setCheckedStateForView===checkedView=111>>>
					+ checkedView);
		}
	}

	public void check(int id) {
		// don't even bother
		Log.i(TAG2, check=000======>>> + id);
		Log.i(TAG2, check=000=11=====>>> + mCheckedId);
		if (id != -1 && (id == mCheckedId)) {
			Log.i(TAG2, check=111======>>> + id);
			return;
		}

		if (mCheckedId != -1) {
			Log.i(TAG2, check=222======>>> + id);
			setCheckedStateForView(mCheckedId, false);
		}

		if (id != -1) {
			Log.i(TAG2, check=333======>>> + id);
			setCheckedStateForView(id, true);
		}

		setCheckedId(id);
	}

	/**
	 * 選擇Item後要執行的操作
	 * 
	 * @param id
	 */
	private void setCheckedId(int id) {
		// 更新當前選擇的Item的id
		mCheckedId = id;
		if (listener != null) {
			RechargeValueLayout view = (RechargeValueLayout)findViewById(id);
			
			listener.onItemClick(this, id,view.getMoneyValue());
		}
	}

	/**
	 * 設置點擊item的監聽
	 * 
	 * @param l
	 */
	public void setOnItemTabClickListener(OnItemTabClickListener l) {
		this.listener = l;
	}

	/**
	 * item選擇監聽 Title: RechargeValueGroup.java Description:
	 * 
	 * @author Liusong
	 * @date 2015-6-26
	 * @version V1.0
	 */
	public interface OnItemTabClickListener {
		public void onItemClick(RechargeValueGroupview, int checkedId,String money);
	}

	/**
	 * 圖層變換監聽 Title: RechargeValueGroup.java Description:
	 * 
	 * @author Liusong
	 * @date 2015-6-26
	 * @version V1.0
	 */
	private class PassThroughHierarchyChangeListener implements
			ViewGroup.OnHierarchyChangeListener {
		private ViewGroup.OnHierarchyChangeListener mOnHierarchyChangeListener;

		/**
		 * {@inheritDoc}
		 */
		public void onChildViewAdded(View parent, View child) {
			if (parent == RechargeValueTabHost.this
					&& child instanceof RechargeValueLayout) {
				int id = child.getId();
//				Log.i(TAG2, onChildViewAdded=111==>>>> + id);
				// generates an id if it's missing
				if (id == View.NO_ID) {
					id = View.generateViewId();
					child.setId(id);
				}
				tabChildsId.add(id);
				((RechargeValueLayout) child)
						.setOnClickListener(mChildOnCheckedChangeListener);
			}

			if (mOnHierarchyChangeListener != null) {
				mOnHierarchyChangeListener.onChildViewAdded(parent, child);
			}
		}

		/**
		 * {@inheritDoc}
		 */
		public void onChildViewRemoved(View parent, View child) {
			if (parent == RechargeValueTabHost.this
					&& child instanceof RechargeValueLayout) {
				((RechargeValueLayout) child).setOnClickListener(null);
				tabChildsId.remove(child.getId());
			}
//			Log.i(TAG2, onChildViewRemoved=111==>>>> + child.getId());
			if (mOnHierarchyChangeListener != null) {
				mOnHierarchyChangeListener.onChildViewRemoved(parent, child);
			}
		}
	}

	/**
	 * 每一項Item的點擊事件 Title: RechargeValueGroup.java Description:
	 * 
	 * @author Liusong
	 * @date 2015-6-26
	 * @version V1.0
	 */
	class CheckedStateTracker implements OnClickListener {

		@Override
		public void onClick(View v) {
//			setCheckedId(v.getId());
			check(v.getId());
		}

	};

//	/**
//	 * Item的具體數據值 Title: RechargeValueGroup.java Description:
//	 * 
//	 * @author Liusong
//	 * @date 2015-6-26
//	 * @version V1.0
//	 */
//	class RechargeValueBean {
//		public int zengs;
//		public int money;
//		public int cords;
//	}
}


就上上面的代碼,由於我是使用的在Xml裡面添加子控件,所以就沒寫addView方法,有興趣的可以自己寫一下addview方法。

然後,我有加了一個public void setDataOfTabs(List datas)這個方法,就是把得到的數據直接付給這個控件,這樣,就會自動把所有子控件附上值。

這樣比較方便,因為數據是從服務器拿到的,使用Gson工具類,直接把數據封裝成了集合,只要把集合傳入就可實現自動賦值。非常方便,自己不需要一個一個的去賦值了。

 

根據RadioCroup修改的,只要根據不同的情況稍作修改就可以滿足很多情況,例如,我們常見的底部導航,tab選擇等等,只要我們稍把不同的item子控件改動一下,我們就會很快的實現一個單選樣式的按鈕組。

 

使用方法也很簡單,在代碼中

mRechargeGroup= (RechargeValueGroup) findViewById(R.id.rechargeGroup);
  mRechargeGroup.setOnItemTabClickListener(new OnItemTabClickListener() {

   @Override
   public void onItemClick(RechargeValueGroupview, int checkedId,String money) {
    // TODO Auto-generated method stub
    Log.i(TAG2, checkedId===>>>+checkedId);
    realPrice = money;
   }
   
  });


找到控件設置監聽,然後回掉回來各種參數,id等,我們也可以根據自己的需求去修改OnItemTabClickListener監聽接口中的onItemClick傳遞的參數來滿足自己的需求,

然後我們在適當的地方調用setDataOfTabs(List datas)這個方法來設置數據就好了。

xml裡面,就是上面的那段代碼



            
            

            
            

            
            
            
        


就這麼簡單,大家可以在這個基礎上來進行其他擴展什麼的。

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved