毕设应用中需要添加一个滑动按钮,在网上看了几个Demo之后决定自定义ViewGroup来实现。
这里是对实现过程中自定义ViewGroup的方法总结。
关于ViewGroup,文档给出的描述是:
A ViewGroup
is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers.
ViewGroup是一种可以包含其他视图的特殊视图,是布局和其他视图容器的基类。
正因为ViewGroup可以包含多个视图,所以在实现滑动按钮时可以使用它(一个主视图,一个按钮视图)。
以自定义ViewGroup的名称创建一个类,继承ViewGroup
- public class SlidingMenuView extends ViewGroup {
- public SlidingMenuView(Context context, AttributeSet attrs) {
- super(context, attrs);
- // TODO Auto-generated constructor stub
- }
- @Override
- protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
- // TODO Auto-generated method stub
- }
- }
继承ViewGroup之后,eclipse提示需要生成自定义ViewGroup的构造方法和onLayout方法。
onLayout方法是ViewGroup中的抽象方法,因此继承ViewGroup之后一定要实现该方法。Called from layout when this view should assign a size and position to each of its children. Derived classes with children should override this method and call layout on each of their children.
Parameters:
changed
This is a new size or position for this view
l
Left position, relative to parent
t
Top position, relative to parent
r
Right position, relative to parent
b
Bottom position, relative to parent
ViewGroup中的onLayout方法将在ViewGroup为它的孩子们分配尺寸和位置的时候被调用,在这个类的实现中,需要调用每一个控件的布局方法为其布局。
注意:onLayout在View中是一个public的方法,在ViewGroup为protected类型,并且为abstract,由于这个方法在ViewGroup中没有实现,因此ViewGroup本身不可以直接使用。
创建布局文件myalbumlistwithmuen,使用MyViewGroup作为控件:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
- <com.album.view.SlidingMenuView
- android:id="@+id/myviewgroup"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
- </com.album.view.SlidingMenuView>
- </LinearLayout>
创建如图两个子视图:主页面myalbumlist、按钮页面slidingmenu:
创建Activity,使用myalbumlistwithmuen作为其布局:
- public class MyAlbumListActivity extends Activity {
- private MyViewGroup myViewGroup;
- private LayoutInflater layoutInflater;
- private View slidingmenu, myalbumlist;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.myalbumlistwithmuen);
- initView();
- }
- private void initView(){
- myViewGroup=(MyViewGroup)findViewById(R.id.myviewgroup);
- layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
- slidingmenu = layoutInflater.inflate(R.layout.slidingmenu, null);
- myalbumlist=layoutInflater.inflate(R.layout.myalbumlist, null);
- myViewGroup.addView(slidingmenu); //添加滑动菜单的view
- myViewGroup.addView(myalbumlist); //添加主页面的view
- }
- }
- @Override
- protected void onLayout(boolean changed, int l, int t, int r, int b) {
- if (changed) {
- slidingmenu = getChildAt(0);// 获取滑动菜单的view
- myalbumlist = getChildAt(1);// 获得主页view
- // 相当于fill_parent
- myalbumlist.measure(0, 0);
- myalbumlist.layout(0, 0, getWidth(), getHeight());
- }
- }