Android Studio:无法根据布尔值更改背景颜色和文本颜色
Android Studio: Unable to change background color and text color based on boolean
我正在构建一个待办事项应用程序。如果 urgent = true (boolean),我的目标是将项目的背景颜色更改为红色并将字体更改为白色。
我可以做到这一点,但不幸的是一旦它改变了真正的todo,它也会改变之前的todo,即使它等于false。
我知道问题出在 getView 方法中(见下文)。我尝试将 textView = newView.findViewById(R.id.textView) 移动到 if old == null 语句上方,但这似乎会使应用程序崩溃。我还把 if urgent == true 语句移到了另一个 if 语句中,这也不起作用。
任何可能导致问题的想法?
@Override
public View getView(int position, View old, ViewGroup parent) {
View newView = old;
LayoutInflater inflater = getLayoutInflater();
if(old == null) {
newView = inflater.inflate(R.layout.todo_items, parent, false);
}
textView = newView.findViewById(R.id.textView);
textView.setText(getItem(position).toString());
if(urgent == true) {
newView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.WHITE);
}
return newView;
}
}
我认为您需要为列表中的每个位置创建一个包含 urgent
个变量的数组(或列表)。当列表中的项目因其他原因滚动更新时,所有视图都根据一个 urgent
var.
更新
您需要一个布尔数组来跟踪列表视图中每个项目的状态
尝试改变
if(urgent == true) {
newView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.WHITE);
}
到
if(urgent[position]) {
newView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.WHITE);
} else {
//Put here the default colors
newView.setBackgroundColor( );
textView.setTextColor( );
}
这应该可以解决问题,您也不需要这样做 if(boolean == true)
if(boolean)
就足够了
我正在构建一个待办事项应用程序。如果 urgent = true (boolean),我的目标是将项目的背景颜色更改为红色并将字体更改为白色。
我可以做到这一点,但不幸的是一旦它改变了真正的todo,它也会改变之前的todo,即使它等于false。
我知道问题出在 getView 方法中(见下文)。我尝试将 textView = newView.findViewById(R.id.textView) 移动到 if old == null 语句上方,但这似乎会使应用程序崩溃。我还把 if urgent == true 语句移到了另一个 if 语句中,这也不起作用。
任何可能导致问题的想法?
@Override
public View getView(int position, View old, ViewGroup parent) {
View newView = old;
LayoutInflater inflater = getLayoutInflater();
if(old == null) {
newView = inflater.inflate(R.layout.todo_items, parent, false);
}
textView = newView.findViewById(R.id.textView);
textView.setText(getItem(position).toString());
if(urgent == true) {
newView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.WHITE);
}
return newView;
}
}
我认为您需要为列表中的每个位置创建一个包含 urgent
个变量的数组(或列表)。当列表中的项目因其他原因滚动更新时,所有视图都根据一个 urgent
var.
您需要一个布尔数组来跟踪列表视图中每个项目的状态
尝试改变
if(urgent == true) {
newView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.WHITE);
}
到
if(urgent[position]) {
newView.setBackgroundColor(Color.RED);
textView.setTextColor(Color.WHITE);
} else {
//Put here the default colors
newView.setBackgroundColor( );
textView.setTextColor( );
}
这应该可以解决问题,您也不需要这样做 if(boolean == true)
if(boolean)
就足够了