view方法setId理解及动态添加组件含style样式

更新2013-1-8:

R文件存储的id是C语言的十六进制表示法。 以0x开头,在java中,会自动转成10进制。所以,如下等式是成立的:

View m=(View)findViewById(R.id.myview);

ture==(m.getId()==R.id.myview)

故后面setId()的理解,可以不用看啦。呵呵,献丑了

 

 

1. view setId方法理解

view.setId()方法和android:id配置一样。除了具有唯一标识外,还有配置android:id的功能.如setId(1)就可以通过findViewById(1)来找到这个View

但是有一点需要强调, 多个组件不能用同一个ID,否则像onclick或者onSelect事件不会响应。

以下是使用RadioButton做的例子: main里存在RadioGroup组件, 通过LayoutFlater生成带style的radioButton,并加入至RadioGroup.为了让它们成为一组,必须赋予不同的id(或者配置文件与代码都不设置id,也可以)

以下是代码生成动态组件,得到的toast结果是对应view的setID里的值

linear = (RadioGroup)findViewById(R.id.linear2);
RadioButton view=(RadioButton)LayoutInflater.from(this).inflate(R.layout.bt, null);
view.setId(3);
linear.addView(view);
RadioButton view2=(RadioButton)LayoutInflater.from(this).inflate(R.layout.bt, null);
view2.setId(4);
linear.addView(view2);
linear.setOnCheckedChangeListener(new OnCheckedChangeListener() {
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		Toast.makeText(TestActivity.this,"checkedId:"+checkedId, 100).show();
		RadioButton rButton=(RadioButton)linear.findViewById(4);
		Toast.makeText(TestActivity.this,"rButton:"+rButton.getId(), 300).show();
	}
});


RadioButton的XML配置

<?xml version="1.0" encoding="utf-8" ?>
<RadioButton android:text="隐藏" android:layout_width="fill_parent" 
style="@style/rb_darkBlue"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" />


 

 

2. 动态添加组件含style样式

一般情况下都有以下需求:

动态添加某个组件 ,可这个组件因为美化的原因,引用了style资源。

相信很多人试过,view.setStyle这个方法是没有的,而完全用一项项设置(如setTextSize setBackgroud等)代码去替换Style属性,非常困难且达到原效果不效。

那么是否有一种解决方法呢?

有,那就是通过LayoutFlater加载为BUTTON的配置文件,配置文件设置好style, 并且不要设置id(多个组件不能使用同一ID)

RadioButton.xml

<?xml version="1.0" encoding="utf-8" ?>
<RadioButton android:text="隐藏" android:layout_width="fill_parent" 
 xmlns:android=http://schemas.android.com/apk/res/android
style="@style/rb_darkBlue"
android:layout_height="wrap_content" />


动态生成代码:

linear = (RadioGroup)findViewById(R.id.linear2);
RadioButton view=(RadioButton)LayoutInflater.from(this).inflate(R.layout.bt, null);
//view.setId(3);
linear.addView(view);
RadioButton view2=(RadioButton)LayoutInflater.from(this).inflate(R.layout.bt, null);
//view2.setId(4);
linear.addView(view2);
RadioButton view3=(RadioButton)LayoutInflater.from(this).inflate(R.layout.bt, null);
//view3.setId(5);
linear.addView(view3);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值