【问题标题】:Selecting particular no of images from multiselect gridView从多选 gridView 中选择特定数量的图像
【发布时间】:2015-04-06 19:14:56
【问题描述】:

我设计了一个多选 gridView,我在其中将多个图像显示为网格项。当用户单击任何图像时,我将前景图像添加到该特定图像,以便用户知道他选择了多少图像。我的要求是我想限制用户选择最多 8 个图像,这意味着每当用户尝试从 gridView 中选择第 9 个(超过 8 个)项目时,我的程序不应该将前景图像添加到第 9 个项目。

public class MultiImagePicActivity extends Activity {

GridView mGrid;


private String[] arrPath,modifiedArrayPath;
private int ids[];
private int count;
static int selectCount;
Activity act=this;
Context ctx=this;
List<String> imagepaths;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    imagepaths=new ArrayList<String>();
    imagepaths.clear();
    loadApps();

    setContentView(R.layout.grid_1);
    mGrid = (GridView) findViewById(R.id.myGrid);

    mGrid.setAdapter(new ImageAdapterxtends());

    mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
    mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener());

}

    private void loadApps() {




    final String[] columns = { MediaStore.Images.Media.DATA,  MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    Cursor imagecursor =  getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,  columns, null, null, orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
    this.count = imagecursor.getCount();
    this.arrPath = new String[this.count];
    ids = new int[count];
    for (int i = 0; i <this.count; i++) {
        imagecursor.moveToPosition(i);
        ids[i] = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        arrPath[i] = imagecursor.getString(dataColumnIndex);
    }

    imagecursor.close();

}
@Override
public void onBackPressed() {
    setResult(Activity.RESULT_CANCELED);
    super.onBackPressed();

}
public class ImageAdapterxtends extends BaseAdapter{
    CheckableLayout l;
    ImageView i;

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return arrPath.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return arrPath[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        if (convertView == null) {
            i = new ImageView(MultiImagePicActivity.this);
            i.setScaleType(ImageView.ScaleType.FIT_CENTER);
            i.setLayoutParams(new ViewGroup.LayoutParams(50, 50));
            l = new CheckableLayout(MultiImagePicActivity.this);
            l.setLayoutParams(new GridView.LayoutParams(
                    GridView.LayoutParams.WRAP_CONTENT,
                    GridView.LayoutParams.WRAP_CONTENT));
            l.addView(i);
        } else {
            l = (CheckableLayout) convertView;
            i = (ImageView) l.getChildAt(0);
        }
        try {
            setBitmap(i, ids[position]);
        } catch (Throwable e) {
        }
        return l;

    }


    }

    private void setBitmap(final ImageView iv,final int id) {

        new AsyncTask<Void, Void, Bitmap>() {
            Bitmap myBitmap;
            @Override
            protected Bitmap doInBackground(Void... params) {
                return  MediaStore.Images.Thumbnails.getThumbnail(getApplicationContext().getContentResolver(), id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                super.onPostExecute(result);
                //iv.setImageBitmap(result);
                setMyBitmap(result);
            }
            public final void setMyBitmap(Bitmap bitmap) {

                  if (this.myBitmap != null) {
                    this.myBitmap.recycle();
                  }
                  this.myBitmap = bitmap;
                  iv.getLayoutParams().height = 100;
                  iv.getLayoutParams().width = 100;
                  iv.setImageBitmap(myBitmap);
                }
        }.execute();
    }


public class CheckableLayout extends FrameLayout implements Checkable {
    private boolean mChecked;

    public CheckableLayout(Context context) {
        super(context);
    }

    public void setChecked(boolean checked) {

        mChecked = checked;

        setForeground(checked ? getResources().getDrawable(R.drawable.tr) : null);              
        }

    public boolean isChecked() {
        return mChecked;
    }

    public void toggle() {
        selectCount--;
        setChecked(!mChecked);
    }

 }

public class MultiChoiceModeListener implements
        GridView.MultiChoiceModeListener {
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // Inflate the menu for the CAB
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
        //return true;
        mode.setTitle("Select Items");
        mode.setSubtitle("One item selected");
        return true;
    }

    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return true;
    }

    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        // Respond to clicks on the actions in the CAB
        switch (item.getItemId()) {
            case R.id.menu_ok:
            Intent i = new Intent();
                modifiedArrayPath=imagepaths.toArray(new String[imagepaths.size()]);
                i.putExtra("selectedImagepath", modifiedArrayPath);
                //i.putExtra("data", selectedPath);
                setResult(Activity.RESULT_OK, i);
                return true;
            default:
                return false;
        }
    }

    public void onDestroyActionMode(ActionMode mode) {
        Toast.makeText(getApplicationContext(), "text", 1);
    }

    public void onItemCheckedStateChanged(ActionMode mode, int position,
            long id, boolean checked) {
        selectCount = mGrid.getCheckedItemCount();
        if(checked){
        if(selectCount>8){
            imagepaths.remove(arrPath[position]);
            new AlertDialog.Builder(MultiImagePicActivity.this)
            .setTitle("Restriction")
            .setMessage("Max 8 images are allowed!!!")
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) { 
                    dialog.dismiss();
                }
             })
            .setIcon(android.R.drawable.ic_dialog_alert)
             .show();
        }
        switch (selectCount) {
        case 1:
            mode.setSubtitle("One item selected");
            break;
        default:
            mode.setSubtitle("" + selectCount + " items selected");
            break;
        }
    }
    }
}
}

【问题讨论】:

  • 如您所见,我已经在我的程序中使用了 public int getCheckedItemCount () 来检查检查的图像数量。我的设备中也出现警告弹出窗口。但问题是我的程序仍在添加前景图像到第 9、10 个.....元素。如何限制此操作。
  • 你在哪里添加前景图像?哪一行?
  • 我相信你应该检查是否应该在 getView 中设置位图而不考虑你的要求,检查这一行 setBitmap(i, ids[position])
  • @random 先生,是的,它工作正常..

标签: android android-gridview


【解决方案1】:

你可以试试,

在你的类中定义静态变量,

private static int count = 0;

然后更新你的方法如下,

public void setChecked(boolean checked) 
{
    if(count < 9)
    {
        mChecked = checked;
        setForeground(checked ? getResources().getDrawable(R.drawable.tr) : null);    
        count = count + 1;          
    }
    else
    {
        //prompt the dialog here
    } 
}

同时确保在退出活动时重置变量。

【讨论】:

  • 我已经绑定了这个逻辑,先生。但它对我不起作用。只要此活动已加载到设备中,它就会直接执行 else 部分。
  • 先生,我给定的活动类是唯一的类。我以编程方式设计了我的 UI,正如您在我的程序中看到的那样。
  • 先生,您能否对我的代码进行必要的修改,并给我正确的代码来实现这个目标。
  • 您可以调试并查看计数是否正确更新?
猜你喜欢
  • 1970-01-01
  • 2016-03-05
  • 1970-01-01
  • 2019-05-28
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多