本文主要是介绍Android中GridView实现长按多选功能,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
前言:GridView可用于展示多行多列的统一格式数据,但本身没有多选操作。现通过一系列代码实现GridView的长按多选操作,可以先看一个示例图。
以下是实现该功能的主要代码:
MainActivity.java
package com.mygridview;import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;import java.util.ArrayList;
import java.util.HashMap;public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {private ActionBar actionBar;private Button btnCancel, btnDel, btnSelectAll, btnClear;private RelativeLayout headerLayout;private TextView numText;private GridView gridView;private ArrayList<HashMap<String, Object>> items; //每一个itemprivate ArrayList<Boolean> selectItems; //用于存储已选中项目的位置private MyAdapter adapter;private boolean isState;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();}private void initView() {actionBar = getSupportActionBar();actionBar.setTitle("GridView");numText = (TextView) findViewById(R.id.number);btnCancel = (Button) findViewById(R.id.btn_cancel);btnDel = (Button) findViewById(R.id.btn_del);btnSelectAll = (Button) findViewById(R.id.btn_select_all);btnClear = (Button) findViewById(R.id.btn_clear);btnCancel.setOnClickListener(this);btnDel.setOnClickListener(this);btnSelectAll.setOnClickListener(this);btnClear.setOnClickListener(this);headerLayout = (RelativeLayout) findViewById(R.id.header);gridView = (GridView) findViewById(R.id.grid_view);items = new ArrayList<>();selectItems = new ArrayList<>();for (int i = 0; i < 20; i++) {HashMap<String, Object> item = new HashMap<>();item.put("image", R.drawable.image);items.add(item);}adapter = new MyAdapter(this, items, R.layout.image, new String[]{"image"}, new int[]{R.id.my_image});gridView.setAdapter(adapter);gridView.setOnItemClickListener(this);gridView.setOnItemLongClickListener(this);}public ArrayList<Boolean> getSelectItems() {return selectItems;}@Overridepublic void onClick(View v) {switch (v.getId()) {case R.id.btn_cancel :selectItems.clear();numText.setText("已选择1项");adapter.setIsState(false);setState(
这篇关于Android中GridView实现长按多选功能的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!