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

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

[size=medium]方法1[/size]
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);
}


[size=medium]方法2[/size]
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了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值