两种 Custom View跟xml 结合使用的方法

两种 Custom View和xml 结合使用的方法
有时候我们需要把几个View 放在一起作为一个重复使用的新的View来用。
这时候里面的view,用xml来组织比较方便。下面介绍两种方法。

方法1
1. 定义CustomView.java extends XxxLayout
2. 在CustomView里面inflate 需要的资源文件,然后把它加到当前的View里面
3. 这个CustomView.java可以写在自己的layout文件里面用了。

举个例子,MediaController.java,这个在Android源码里面。
framework/base/core/java/android/widget/

    protected View makeControllerView() {
	log("makeControllerView");
        LayoutInflater inflate = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mRoot = inflate.inflate(com.android.internal.R.layout.media_controller, null);

        initControllerView(mRoot);

        return mRoot;
    }

    public void setAnchorView(View view) {
        mAnchor = view;

        FrameLayout.LayoutParams frameParams = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.FILL_PARENT
        );

        removeAllViews();
        View v = makeControllerView();
        addView(v, frameParams);
    }


方法2
1. 定义CustomView.java extends XxxLayout
2. 在layout文件里面直接用这个View, 它就是原来的Layout,直接把TextView, ImageView什么的,放在里面。
3. 在CustomeView.java里面对放进去的view findViewById就可以灵活处理了。

举个例子, TabHost.java,
framework/base/core/java/android/widget/

public class TabHost extends FrameLayout 
...
    public void setup() {
        mTabWidget = (TabWidget) findViewById(com.android.internal.R.id.tabs);
        if (mTabWidget == null) {
            throw new RuntimeException(
                    "Your TabHost must have a TabWidget whose id attribute is 'android.R.id.tabs'");
        }
...
}

tab_content.xml
<TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost"
	android:layout_width="fill_parent" android:layout_height="fill_parent">
	<LinearLayout android:orientation="vertical"
    	android:layout_width="fill_parent" android:layout_height="fill_parent">
        <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent"
        	android:layout_height="wrap_content" android:layout_weight="0" />
        <FrameLayout android:id="@android:id/tabcontent"
        	android:layout_width="fill_parent" android:layout_height="0dip"
            android:layout_weight="1"/>
	</LinearLayout>
</TabHost>


第2种方法好像比较有意思,也不用addView了。