您的位置:首页 > 其它

XML中控件的id与findViewById()的相关问题

2015-03-27 20:01 295 查看
  写了一个测试的小程序,编译过程中没有报任何错误,也能安装到模拟器里,但是在运行程序的时候点击跳转按钮,程序停止运行并退出,查看Mainfest文件里Activity也注册了,百思不得其解,好半天才发现问题所在。

  我在layout里新建了三个XML,在任何一个XML文件里控件的id没有重复的,但是在另外的XML文件的控件id是相同的,于是通过findviewbyid()找地址的时候都指向了第一个xml文件的控件id,点击跳转时,系统找不到控件id自然会崩溃。

  就是说不管有几个xml,不管在不在一个xml文件里,里面控件的id是不可以重复的

  现在还不知道findviewbyid()的原理是什么,我想应该有更简单的方法,不同xml里的控件id是可以相同的,但是我还不知道,吾将上下而求索

  下面贴上那个小程序的java代码,是一个RadioGroup和onCheckedChangeListener用法的练习

  

  

public class Second extends Activity {

private View sec;
private RadioButton a2;
private RadioButton b2;
private RadioButton c2;
private RadioGroup radioGroup2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);

radioGroup2=(RadioGroup)findViewById(R.id.rgp2);
a2=(RadioButton)findViewById(R.id.rbt_a2);
b2=(RadioButton)findViewById(R.id.rbt_b2);
c2=(RadioButton)findViewById(R.id.rbt_c2);

RightC jump=new RightC();
radioGroup2.setOnCheckedChangeListener(jump);
}

class RightC implements OnCheckedChangeListener{

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId==c2.getId()){
c2.setBackgroundColor(Color.rgb(0, 255, 0));
Intent intent =new Intent();
intent.setClass(Second.this, Third.class);
startActivity(intent);
}
else{
if(checkedId==a2.getId()){

a2.setBackgroundColor(Color.rgb(255,192,203));
b2.setBackgroundColor(Color.TRANSPARENT);
c2.setBackgroundColor(Color.TRANSPARENT);

}
else{
b2.setBackgroundColor(Color.rgb(255,192,203));
a2.setBackgroundColor(Color.TRANSPARENT);
c2.setBackgroundColor(Color.TRANSPARENT);

}
}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: