Java Gridview在滚动时更改其视图
我想在选中时更改网格项目的文本颜色,并且一次只能选择一个项目,这已经完成,但是如果gridview有许多项目,如果我选择任何项目并滚动gridview,那么它将选择网格中的随机项目,并允许选择多个项目。 我尝试了许多答案,但没有找到任何单一的解决办法。 有人知道吗 我尝试了下面链接给出的答案,但并没有解决我的问题 我将与网格视图的适配器getView方法和onItemSelected()方法共享我的代码Java Gridview在滚动时更改其视图,java,android,xml,gridview,Java,Android,Xml,Gridview,我想在选中时更改网格项目的文本颜色,并且一次只能选择一个项目,这已经完成,但是如果gridview有许多项目,如果我选择任何项目并滚动gridview,那么它将选择网格中的随机项目,并允许选择多个项目。 我尝试了许多答案,但没有找到任何单一的解决办法。 有人知道吗 我尝试了下面链接给出的答案,但并没有解决我的问题 我将与网格视图的适配器getView方法和onItemSelected()方法共享我的代码 gridview.setOnItemClickListener(new AdapterV
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long arg3) {
view.setSelected(true);
TextView tv = (TextView) view; // Get the current selected view as a TextView
tv.setTextColor(Color.parseColor("#50d1e4")); // Set the current selected item text color
TextView previousSelectedView = (TextView) gridview.getChildAt(previousPosition); // Get the last selected View from GridView
// If there is a previous selected view exists
if (previousPosition != -1 && previousPosition!=position) {
previousSelectedView.setSelected(false); // Set the last selected View to deselect
previousSelectedView.setTextColor(Color.parseColor("#162750")); // Set the last selected View text color as deselected item
}
previousPosition = position;
}
});
下面是grid_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/txt_item_time_slot"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="10:20 AM"
android:gravity="center_horizontal"
android:padding="3dp"
android:textColor="#162750"
android:textStyle="bold"
android:textSize="30sp"/>
无需添加previousPosition变量。 在模型中添加一个参数。您有任何模型的列表,添加一个参数isSelected(布尔值)。当用户单击它时,将其设置为true 在适配器的getView方法中,检查项的isSelected值。您可以从列表(listValue.get(position.isSelected())中获取它。根据返回值,您可以更改背景。它还可以帮助您获取选定的值 例如:
Product product = mProcucts.get(position);
itemViewHolder.textView.setText(product.getProductName());
if(product.isSelected()){ itemViewHolder.textView.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.shape_button_checked));
}else{
itemViewHolder.textView.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.shape_button_unchecked));
}
实际上,这些并不是随机项,而是被“选中”的重用项(您称之为setSelected)。您应该在适配器中处理选择/取消选择状态。谢谢@danypata,我现在就来试试
Product product = mProcucts.get(position);
itemViewHolder.textView.setText(product.getProductName());
if(product.isSelected()){ itemViewHolder.textView.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.shape_button_checked));
}else{
itemViewHolder.textView.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.shape_button_unchecked));
}