Android中ViewGroup等容器控制項的使用

來源:互聯網
上載者:User

 

在Android中,可以自訂類,繼承ViewGroup等容器類,以實現自己需要的布局顯示。

 

如果你在ViewGroup中增加了控制項,卻無法顯示出來,那麼下面這個例子,就可以用來參考了。

 

(主要是要實現onLayout()方法,在這個方法中,對每個子控制項進行measure(),然後再布局。)

 

package com.arui;<br />import android.content.Context;<br />import android.util.Log;<br />import android.view.View;<br />import android.view.ViewGroup;<br />import android.widget.Button;<br />/**<br /> * Example for using ViewGroup.<br /> *<br /> * @author http://blog.csdn.net/arui319<br /> * @version 2010/09/07<br /> *<br /> */<br />public class MyViewGroup extends ViewGroup {<br />public MyViewGroup(Context context) {<br />super(context);<br />this.initOtherComponent(context);<br />}<br />private void initOtherComponent(Context context) {<br />Button aBtn = new Button(context);<br />// set id 1<br />aBtn.setId(1);<br />aBtn.setText("a btn");<br />this.addView(aBtn);<br />Button bBtn = new Button(context);<br />// set id 2<br />bBtn.setId(2);<br />bBtn.setText("b btn");<br />this.addView(bBtn);<br />}<br />@Override<br />protected void onLayout(boolean changed, int l, int t, int r, int b) {<br />int childCount = getChildCount();<br />for (int i = 0; i < childCount; i++) {<br />View child = getChildAt(i);<br />switch (child.getId()) {<br />case 1:<br />// 1 is aBtn<br />Log.d("MyViewGroup", "btn1 setting");<br />child.setVisibility(View.VISIBLE);<br />child.measure(r - l, b - t);<br />child.layout(0, 0, child.getMeasuredWidth(), child<br />.getMeasuredHeight());<br />break;<br />case 2:<br />// 2 is bBtn<br />Log.d("MyViewGroup", "btn2 setting");<br />child.setVisibility(View.VISIBLE);<br />child.measure(r - l, b - t);<br />child.layout(0, 50, child.getMeasuredWidth(), child<br />.getMeasuredHeight() + 50);<br />break;<br />default:<br />//<br />}<br />}<br />}<br />}<br /> 

 

聯繫我們

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