我写了一个简单的test安卓程序,就是点击菜单textview中的文字变色,这个程序是在上一个练习--实现listview显示列表,然后我发现虽然我引用的都是同一个控件,但是只有textview中的文字变色了,可是listview中的文字却没有变色,实在想不明白,莫非不是同一个textview控件吗????
补上源代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tv);//这里我引用了布局文件中的控件
lv = (ListView) findViewById(R.id.lv);
//这里我用baseadpter和listview实现了列表输出,在mybaseadapter中我也同样引用了相同的tv
MyBaseAdapter mba = new MyBaseAdapter(MainActivity.this, getData());
lv.setAdapter(mba);
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
//监听菜单选项并定义了监听事件,改变tv的字体颜色
@Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.it1:
tv.setTextColor(Color.BLUE);
break;
case R.id.it2:
tv.setTextColor(Color.RED);
break;
case R.id.it3:
tv.setTextColor(Color.BLACK);
break;
case R.id.it4:
break;
case R.id.it5:
tv.setTextColor(Color.YELLOW);
break;
case R.id.it6:
tv.setTextColor(Color.GREEN);
break;
}
return true;
}
当前activity中的tv = (TextView) findViewById(R.id.tv);操作tv控件对象是没问题的。你说在MyBaseAdapter中也引用了tv对象,如何引用的,
是否考虑到UI在主线程更新的问题,
tv = (TextView) findViewById(R.id.tv);
看看是不是你找控件的问题,一个控件就是一个控件,无论你定义几个变量指向它。
在mybaseadapter中我也同样引用了相同的tv, 一个变量只能指向一个实例。如果在listview也有,那也是不同的实例。固不能改变,这里你可以设一个全局的颜色变量,然后刷新listview!
Id只是view的一个属性而已,并不是唯一的。