我实现并激活了 GridView
mGridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
模式。现在,当我长按一个项目时,我可以从我的网格中选择多个项目。我想通过正常的短按来实现此行为。这可能吗?
最佳答案
首先,我建议考虑这个用户场景是否正是您一直在寻找的。默认情况下,在 Android UX 中选择你长按的东西,这是用户习惯的模式。所以,也许您应该重新考虑整个流程。
话说,你真的需要GridView.CHOICE_MODE_MULTIPLE_MODAL
吗?
您可以在适配器级别处理它,只需存储选定的位置并在 onClick
处理程序中更新此列表:
static final String[] numbers = new String[] {
"A", "B", "C", "D", "E",....
"U", "V", "W", "X", "Y", "Z"};
.....
gridView = (GridView) findViewById(R.id.gridView1);
final CustomAdapter adapter = new CustomAdapter(numbers);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
int selectedIndex = adapter.selectedPositions.indexOf(position);
if (selectedIndex > -1) {
adapter.selectedPositions.remove(selectedIndex);
((CustomView)v).display(false);
} else {
adapter.selectedPositions.add(position);
((CustomView)v).display(true);
}
}
});
自定义 BaseAdapter
以显示自定义 View :
public class CustomAdapter extends BaseAdapter {
private String[] strings;
List<Integer> selectedPositions = new ArrayList<>();
CustomAdapter(String [] strings) {
this.strings = strings;
}
@Override
public int getCount() {
return strings.length;
}
@Override
public Object getItem(int position) {
return strings[position];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
CustomView customView = (convertView == null) ?
new CustomView(MainActivity.this) : (CustomView) convertView;
customView.display(strings[position], selectedPositions.contains(position));
return customView;
}
}
自定义 View (在我的例子中 - 带有 TextView 的单元格)。 XML:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/textView"
android:textColor="#FFF"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="60dp" />
</merge>
代码:
class CustomView extends FrameLayout {
TextView textView;
public CustomView(Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.custom_view, this);
textView = (TextView)getRootView().findViewById(R.id.textView);
}
public void display(String text, boolean isSelected) {
textView.setText(text);
display(isSelected);
}
public void display(boolean isSelected) {
textView.setBackgroundColor(isSelected? Color.RED : Color.LTGRAY);
}
}
关于Android GridView 多选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34492280/