我尝试更改 listView 项目中按钮的背景颜色,但是当我尝试更改背景时,背景每 9 个项目都会更改。 当我尝试更改手机方向时,背景每 5 项更改一次...
---理解图像:
http://image.noelshack.com/fichiers/2014/09/1393436440-problem.png
听不懂,好奇怪。
我创建了一个适配器。
Java.java(不是我的适配器文件)
public void clickPresent(View v)
{
v.setBackgroundColor(Color.BLUE);
}
public void drawStudentsInListView()
{
for (int i = 0; i < this.listStudents.size(); i++)
{
Log.e("STUDENT", this.listStudents.get(i)._firstName);
}
if (listStudents.size() > 0)
{
Student[] weather_data;
weather_data = new Student[listStudents.size()];
for (int i = 0; i < listStudents.size(); i++)
{
weather_data[i] = new Student(listStudents.get(i)._firstName, listStudents.get(i)._lastName);
Log.e("Count nbr student: ", "i = " + i);
}
WeatherAdapter adapter = new WeatherAdapter(this, R.layout.listview_item_row, weather_data);
listView1 = (ListView)findViewById(R.id.listView1);
listView1.setAdapter(adapter);
}
}
listview_item_row.xml
<Button
android:layout_width="100dp"
android:layout_height="30dp"
android:background="#009857"
android:layout_marginLeft="10dp"
android:textColor="#ffffff"
android:text="OK"
android:id="@+id/buttonPresent"
android:onClick="clickPresent" />
适配器.java
public class WeatherAdapter extends ArrayAdapter<Student>
{
Context context;
int layoutResourceId;
Student data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Student[] data)
{
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
WeatherHolder holder = null;
if (row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.firstName = (TextView)row.findViewById(R.id.textFirstName);
holder.lastName = (TextView)row.findViewById(R.id.textLastName);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Student weather = data[position];
holder.firstName.setText(weather._firstName);
holder.lastName.setText(weather._lastName);
return row;
}
static class WeatherHolder
{
TextView firstName;
TextView lastName;
}
}
我不明白问题出在哪里:/
谢谢
最佳答案
为了提高性能,ListView 在滚动时使用旧 View 来填充新 View ,这就是您在其他 View 中看到重复操作的原因。
要解决您的问题,我建议您将 boolean 变量设置为当前项目按钮的标签。
鉴于您的行项目包含(名字,姓氏),请添加一个像这样的新属性按钮。
static class WeatherHolder
{
TextView firstName;
TextView lastName;
Button button
}
像对待其他项目一样在 GetView 上初始化它,然后当您检索学生详细信息时,检查按钮是否有一个等于 True 的标签(=> 表示已单击) 在您的 clickPresent 方法中,只需在单击时设置 True 标记,在取消单击时设置 False 标记。
注意:如果标签等于 false 则重置颜色。
public void clickPresent(View v)
{
v.setBackgroundColor(Color.BLUE);
v.setTag(true);
}
关于java - Bug - ListView -> 项目 -> 按钮 OnClick : Change background color of parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22049108/