Android 如何在我的gridview中添加复选框?

Android 如何在我的gridview中添加复选框?,android,gridview,Android,Gridview,如何在代码中添加复选框?所以用户在gridview中使用复选框选择多张图片我该怎么做?我只想在gridview中添加一个复选框我该怎么做 GridView gridView; TextView textView; File currentParent; File[] currentFiles; SimpleAdapter simpleAdapter; File root1; File root; root1 = new File("/data/data/com.myexample.lock/

如何在代码中添加复选框?所以用户在gridview中使用复选框选择多张图片我该怎么做?我只想在gridview中添加一个复选框我该怎么做

GridView gridView;
TextView textView;
File currentParent;
File[] currentFiles;
SimpleAdapter simpleAdapter;
File root1;
 File root;

root1 = new File("/data/data/com.myexample.lock/files/");

 currentParent = root1;
currentFiles = root1.listFiles();

currentFilePath = new String[currentFiles.length];
int count = 0;

 for (File f : currentFiles) {
 currentFilePath[count] = f.getAbsolutePath();
 count++;
}

 gridView = (GridView) findViewById(R.id.grid);
   gridView.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, 
                                     View view, int position, long id) {
 if (currentFiles[position].isDirectory()) {
     root = new File("/data/data/com.myexample.lock/files/" +    
     FileName(currentFilePath[position]) + "/");
     currentFiles = root.listFiles();
     inflateListView(currentFiles);
 } else if (currentFiles[position].isFile()) {
     openFile(currentFiles[position]);
 }
 }

 });




   private void inflateListView(File[] files) {
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
for (int i = 0; i < files.length; i++) {
    Map<String, Object> listItem = new HashMap<String, Object>();
    if (files[i].isDirectory()) {
       listItem.put("icon", R.drawable.folder);
       listItem.put("fileName", files[i].getName()+
                                         "("+files[i].list().length+")");
    } else {
       listItem.put("icon", files[i]);
    }
    listItems.add(listItem);
  }

 simpleAdapter = new SimpleAdapter(this, 
                                  listItems, R.layout.line,new String[] { 
 "icon", "fileName" }, new int[] { R.id.icon, R.id.file_name });
  }
GridView-GridView;
文本视图文本视图;
当前父文件;
文件[]当前文件;
simpledapter simpledapter;
文件根1;
文件根目录;
root1=新文件(“/data/data/com.myexample.lock/files/”;
currentParent=root1;
currentFiles=root1.listFiles();
currentFilePath=新字符串[currentFiles.length];
整数计数=0;
对于(文件f:currentFiles){
currentFilePath[count]=f.getAbsolutePath();
计数++;
}
gridView=(gridView)findViewById(R.id.grid);
setOnItemClickListener(新的OnItemClickListener(){
公共无效MClick(AdapterView父级、,
视图、整型位置、长id){
如果(currentFiles[position].isDirectory()){
root=新文件(“/data/data/com.myexample.lock/files/”+
文件名(currentFilePath[position])+“/”;
currentFiles=root.listFiles();
充气列表视图(当前文件);
}else if(currentFiles[position].isFile()){
openFile(当前文件[位置]);
}
}
});
私有void inflateListView(文件[]文件){
List listItems=new ArrayList();
对于(int i=0;i
line.xml

      <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
   android:layout_height="fill_parent"
  android:background="#ffffff"
  android:orientation="horizontal"
  android:padding="5dip" >

  <ImageView
    android:id="@+id/icon"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

   <TextView
    android:id="@+id/file_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/icon"
    android:paddingLeft="5dp"
    android:textColor="#000000"
    android:textSize="12dp" />



    </RelativeLayout>


为gridView使用自定义适配器。在getView方法中,您可以为单元格膨胀任何想要的布局

这是我如何使用Imageview和TextView创建自定义listview的示例。我这样做是因为我还想删除listview中选择的多个项目

这是我的java代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DeleteData extends Activity {

    Cursor cursor;
    ListView lv_delete_data;
    static ArrayList<Integer> listOfItemsToDelete;
    SQLiteDatabase database;
    private Category[] categories;
    ArrayList<Category> categoryList;
    private ArrayAdapter<Category> listAdapter;
    ImageView iv_delete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delete_data);

        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        manage_reload_list();

        listOfItemsToDelete = new ArrayList<Integer>();

        iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
        iv_delete.setClickable(true);
        iv_delete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listOfItemsToDelete.isEmpty()) {

                    Toast.makeText(getBaseContext(), "No items selected.",
                            Toast.LENGTH_SHORT).show();
                }

                else {
                    showDialog(
                            "Warning",
                            "Are you sure you want to delete these categories ? This will erase all records attached with it.");
                }
            }
        });

        lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
        lv_delete_data.setAdapter(listAdapter);
        lv_delete_data.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                ImageView imageView = (ImageView) arg1
                        .findViewById(R.id.imageViewSingleRowDeleteData);
                Category category = (Category) imageView.getTag();

                if (category.getChecked() == false) {
                    imageView.setImageResource(R.drawable.set_check);
                    listOfItemsToDelete.add(category.getId());
                    category.setChecked(true);
                } else {
                    imageView.setImageResource(R.drawable.set_basecircle);
                    listOfItemsToDelete.remove((Integer) category.getId());
                    category.setChecked(false);
                }
            }
        });
    }

    private void showDialog(final String title, String message) {

        AlertDialog.Builder adb = new Builder(DeleteData.this);
        adb.setTitle(title);
        adb.setMessage(message);
        adb.setIcon(R.drawable.ic_launcher);
        String btn = "Ok";
        if (title.equals("Warning")) {
            btn = "Yes";
            adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }

        adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {

                if (title.equals("Warning")) {

                    for (int i : listOfItemsToDelete) {

                        // -------first delete from category table-----

//                      database.delete("category", "cat_id=?",
//                              new String[] { i + "" });

                        // ---------delete from category_fields

                        database.delete("category_fields", "cat_id=?",
                                new String[] { i + "" });

                        // --------now fetch rec_id where cat_id =
                        // i-----------------

                        cursor = database.query("records_data",
                                new String[] { "rec_id" }, "cat_id=?",
                                new String[] { i + "" }, null, null, null);
                        if (cursor.getCount() == 0)
                            cursor.close();
                        else {
                            ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
                            while (cursor.moveToNext())
                                al_tmp_rec_id.add(cursor.getInt(0));
                            cursor.close();

                            for (int i1 : al_tmp_rec_id) {
                                database.delete("records_fields_data",
                                        "rec_id=?", new String[] { i1 + "" });

                                database.delete("record_tag_relation",
                                        "rec_id=?", new String[] { i1 + "" });
                            }

                            // ---------delete from records_data-------

                            database.delete("records_data", "cat_id=?",
                                    new String[] { i + "" });

                            cursor.close();
                        }
                    }

                    showDialog("Success",
                            "Categories, with their records, deleted successfully.");
                } else {
                    database.close();
                    listOfItemsToDelete.clear();
                    manage_reload_list();
                    lv_delete_data.setAdapter(listAdapter);
                }
            }
        });

        AlertDialog ad = adb.create();
        ad.show();
    }

    protected void manage_reload_list() {

        loadDatabase();

        categoryList = new ArrayList<Category>();

        // ------first fetch all categories name list-------

        cursor = database.query("category", new String[] { "cat_id",
                "cat_description" }, null, null, null, null, null);
        if (cursor.getCount() == 0) {
            Toast.makeText(getBaseContext(), "No categories found.",
                    Toast.LENGTH_SHORT).show();
            cursor.close();
        } else {

            while (cursor.moveToNext()) {

                categories = new Category[] { new Category(cursor.getInt(0),
                        cursor.getString(1)) };
                categoryList.addAll(Arrays.asList(categories));
            }
            cursor.close();
        }
        listAdapter = new CategoryArrayAdapter(this, categoryList);
    }

    static class Category {

        String cat_name = "";
        int cat_id = 0;
        Boolean checked = false;

        Category(int cat_id, String name) {
            this.cat_name = name;
            this.cat_id = cat_id;
        }

        public int getId() {
            return cat_id;
        }

        public String getCatName() {
            return cat_name;
        }

        public Boolean getChecked() {
            return checked;
        }

        public void setChecked(Boolean checked) {
            this.checked = checked;
        }

        public boolean isChecked() {
            return checked;
        }

        public void toggleChecked() {
            checked = !checked;
        }
    }

    static class CategoryViewHolder {

        ImageView imageViewCheck;
        TextView textViewCategoryName;

        public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
            imageViewCheck = iv_check;
            textViewCategoryName = tv_category_name;
        }

        public ImageView getImageViewCheck() {
            return imageViewCheck;
        }

        public TextView getTextViewCategoryName() {
            return textViewCategoryName;
        }
    }

    static class CategoryArrayAdapter extends ArrayAdapter<Category> {

        LayoutInflater inflater;

        public CategoryArrayAdapter(Context context, List<Category> categoryList) {

            super(context, R.layout.single_row_delete_data,
                    R.id.textViewSingleRowDeleteData, categoryList);
            inflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Category category = (Category) this.getItem(position);

            final ImageView imageViewCheck;
            final TextView textViewCN;

            if (convertView == null) {

                convertView = inflater.inflate(R.layout.single_row_delete_data,
                        null);

                imageViewCheck = (ImageView) convertView
                        .findViewById(R.id.imageViewSingleRowDeleteData);
                textViewCN = (TextView) convertView
                        .findViewById(R.id.textViewSingleRowDeleteData);

                convertView.setTag(new CategoryViewHolder(imageViewCheck,
                        textViewCN));
            }

            else {

                CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
                        .getTag();
                imageViewCheck = viewHolder.getImageViewCheck();
                textViewCN = viewHolder.getTextViewCategoryName();
            }

            imageViewCheck.setFocusable(false);
            imageViewCheck.setFocusableInTouchMode(false);
            imageViewCheck.setClickable(true);
            imageViewCheck.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    ImageView iv = (ImageView) v;
                    Category category = (Category) iv.getTag();

                    if (category.getChecked() == false) {
                        imageViewCheck.setImageResource(R.drawable.set_check);
                        listOfItemsToDelete.add(category.getId());
                        category.setChecked(true);
                    } else {
                        imageViewCheck
                                .setImageResource(R.drawable.set_basecircle);
                        listOfItemsToDelete.remove((Integer) category.getId());
                        category.setChecked(false);
                    }
                }
            });
            imageViewCheck.setTag(category);

            if (category.getChecked() == true)
                imageViewCheck.setImageResource(R.drawable.set_check);
            else
                imageViewCheck.setImageResource(R.drawable.set_basecircle);

            textViewCN.setText(category.getCatName());

            return convertView;
        }
    }

    private void loadDatabase() {
        database = openOrCreateDatabase("WalletAppDatabase.db",
                SQLiteDatabase.OPEN_READWRITE, null);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
import java.util.ArrayList;
导入java.util.array;
导入java.util.List;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.app.AlertDialog.Builder;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.pm.ActivityInfo;
导入android.database.Cursor;
导入android.database.sqlite.SQLiteDatabase;
导入android.os.Bundle;
导入android.view.KeyEvent;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.view.ViewGroup;
导入android.widget.AdapterView;
导入android.widget.AdapterView.OnItemClickListener;
导入android.widget.ArrayAdapter;
导入android.widget.ImageView;
导入android.widget.ListView;
导入android.widget.TextView;
导入android.widget.Toast;
公共类DeleteData扩展活动{
光标;
ListView lv_删除_数据;
静态ArrayList listOfItemsToDelete;
SQLITE数据库;
私有类别[]类别;
ArrayList类别列表;
专用阵列适配器列表适配器;
ImageView iv_删除;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u delete\u数据);
此.setRequestedOrientation(ActivityInfo.SCREEN\u ORIENTATION\u Graphic);
管理重新加载列表();
listOfItemsToDelete=newarraylist();
iv_delete=(ImageView)findViewById(R.id.imageViewDeleteDataDelete);
iv_删除。可点击设置(真);
iv_delete.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
if(listOfItemsToDelete.isEmpty()){
Toast.makeText(getBaseContext(),“未选择任何项。”,
吐司。长度(短)。show();
}
否则{
显示对话框(
“警告”,
“确实要删除这些类别吗?这将删除所有附加的记录。”);
}
}
});
lv_delete_data=(ListView)findViewById(R.id.listViewDeleteData);
lv_delete_data.setAdapter(listAdapter);
lv_delete_data.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
公共链接(AdapterView arg0、视图arg1、内部arg2、,
长arg3){
//TODO自动生成的方法存根
ImageView图像视图=(图像视图)arg1
.findViewById(R.id.imageViewSingleRowDeleteData);
Category Category=(Category)imageView.getTag();
if(category.getChecked()==false){
imageView.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
类别。setChecked(真);
}否则{
imageView.setImageResource(R.drawable.set_基圆);
删除((整数)category.getId());
类别。setChecked(假);
}
}
});
}
私有void showDialog(最终字符串标题、字符串消息){
AlertDialog.Builder adb=新生成器(DeleteData.this);
adb.setTitle(标题);
adb.setMessage(消息);
adb.setIcon(R.drawable.ic_启动器);
字符串btn=“确定”;
如果(标题等于(“警告”)){
btn=“是”;
adb.setNegativeButton(“否”,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
dialog.dismise();
}
});
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    tools:context=".DeleteData" >

    <RelativeLayout
        android:id="@+id/relativeLayoutDeleteDataTopBar"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true" >

        <TextView
            android:id="@+id/textViewDeleteDataScreenTitle"
            style="@style/screen_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delete Data" />

        <ImageView
            android:id="@+id/imageViewDeleteDataDelete"
            android:layout_width="22dp"
            android:layout_height="22dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="10dp"
            android:src="@drawable/set_delete" />

    </RelativeLayout>

    <View
        android:id="@+id/viewDeleteData"
        android:layout_width="match_parent"
        android:layout_height="5dp"
        android:layout_below="@+id/relativeLayoutDeleteDataTopBar"
        android:background="@drawable/shadow" />

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
        android:id="@+id/linearLayoutDeleteDataAdMobBanner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >

      <com.google.ads.AdView
          android:id="@+id/adViewDeleteData"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          ads:adSize="BANNER"
          ads:adUnitId="a1512f50d8c3692"
          ads:loadAdOnCreate="true"
          ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" />

    </LinearLayout>

    <ListView
        android:id="@+id/listViewDeleteData"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="#BDBDBD"
        android:dividerHeight="1dp"
        android:layout_below="@+id/viewDeleteData"
        android:layout_above="@+id/linearLayoutDeleteDataAdMobBanner" >
    </ListView>

</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:padding="15dp" >

    <TextView
        android:id="@+id/textViewSingleRowDeleteData"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        style="@style/listview_only_textview"
        android:text="Category" />

    <ImageView
        android:id="@+id/imageViewSingleRowDeleteData"
        android:layout_width="22dp"
        android:layout_height="22dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:src="@drawable/set_basecircle" />

</RelativeLayout>