当我想在列表视图中设置不同的背景按钮时,我遇到了问题。
public class ColorAdapter extends BaseAdapter{
private LayoutInflater inflater;
private Activity activity;
private String[] colors;
public ColorAdapter(Activity activity, String[] colors){
this.activity=activity;
this.colors=colors;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater==null){
inflater=(LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView ==null){
convertView=inflater.inflate(R.layout.color_layout,null);
}
Button button= (Button) convertView.findViewById(R.id.button);
String thisColor = colors[position].toString();
button.setText(thisColor);
String attributeValue = button.getText().toString().toLowerCase();
if(thisColor == "black"){
button.setBackgroundColor(Color.BLACK);
}
return convertView;
}
}
它没有改变颜色。但是这段代码:
String thisColor = colors[position].toString(); button.setText(thisColor);
将文本设置为"黑色"。我错过了什么?
谢谢。
答案 0 :(得分:0)
我已经更新了我的答案。
for String你需要使用string.equals(“string_value”);
示例:
if(thisColor.equals("black")){
//your code.
}
答案 1 :(得分:0)
试试此代码
public class ColorAdapter extends BaseAdapter{
private LayoutInflater inflater;
private Activity activity;
private int[] colors={Color.BLACK,Color.YELLOW,Color.RED,Color.GREEN};//pass this arrary through constructor
public ColorAdapter(Activity activity){
this.activity=activity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater==null){
inflater=(LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView ==null){
convertView=inflater.inflate(R.layout.color_layout,null);
}
Button button= (Button) convertView.findViewById(R.id.button);
int thisColor = colors[position];
button.setText(thisColor);
String attributeValue = button.getText().toString().toLowerCase();
button.setBackgroundColor(thisColor);
return convertView;
}
}