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

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里的值

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


RadioButton的XML配置

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


 

 

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

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

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

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

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

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

RadioButton.xml

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


动态生成代码:

    1. linear = (RadioGroup)findViewById(R.id.linear2);  
    2. RadioButton view=(RadioButton)LayoutInflater.from(this).inflate(R.layout.bt, null);  
    3. //view.setId(3);  
    4. linear.addView(view);  
    5. RadioButton view2=(RadioButton)LayoutInflater.from(this).inflate(R.layout.bt, null);  
    6. //view2.setId(4);  
    7. linear.addView(view2);  
    8. RadioButton view3=(RadioButton)LayoutInflater.from(this).inflate(R.layout.bt, null);  
    9. //view3.setId(5);  
    10. linear.addView(view3);  
posted @ 2014-05-16 17:28  huidaoli  阅读(646)  评论(0编辑  收藏  举报