我在linearlayout horizontalscrollview中动态创建按钮,然后点击我获得选中按钮位置。然后我改变了点击按钮的文字颜色。但我的问题是我怎么能休息其他按钮的文字颜色。
例如,我在linearlayout horizontalscrollview中有6或7个按钮,当我单击位置1按钮以使其文本颜色发生变化时,但是当我单击位置2按钮时,我想重置位置1或所有按钮文本颜色。我该怎么办?
这是我的代码。
String[] categories = {"SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"};
private LinearLayout ll;
Button btn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.hsvLinearLayout);
for(int i = 0; i < categories.length; i++) {
btn = new Button(this);
btn.setText(categories[i]);
btn.setBackgroundColor(Color.parseColor("#ffffff"));
btn.setOnClickListener(buttonClick);
ll.addView(btn);
int idx = ll.indexOfChild(btn);
btn.setTag(Integer.toString(idx));
}
}
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
if(v instanceof Button){
((Button)v).setTextColor(Color.parseColor("#00aeef"));
}
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};
答案 0 :(得分:2)
也许通过主布局孩子进行一些迭代?
for(int i=0; i<ll.getChildCount(); i++){
if(ll.getChildAt(i) instanceOf Button)
((Button)ll.getChildAt(i)).
setTextColor(Color.parseColor("#00aeef"));
}
您的活动中也不需要Button btn;
,此引用未使用(仅保留最后添加的按钮)