我想在Longpress上更改图像?(所有图像视图都在循环中并动态创建)

时间:2016-11-28 07:39:40

标签: android

现在做这些事情: -

我想在长按时更改图像。我的所有图像视图都在for循环中。 我从todo setId()和getId()方法获得了所有内容。 但是当我这样做时,当前的图像在改变第二个图像时不会改变。

这是我的代码: -

for (int i = 0; i < i1; i++) {//my i1 is number of inputs (which is every time changeble)
image = new ImageView(MainActivity.this);
image.setId(i);
image.setImageResource(R.drawable.bed1);
tables.addView(image);}

图片Longclick听众代码: -

image.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int updateid=v.getId();
editor.putInt("updatedid",updateid).apply();
if(updateid==R.drawable.bed1){
image.setImageResource(R.drawable.hall);
}

buttonGalleryOpen();//open the phone gallery
return false;

}
});

来自图库的开放图片代码: -

public void buttonGalleryOpen()
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, RESULT_LOAD_IMAGE);
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {


    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {

        Uri selectedImage = data.getData();
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String filePath = cursor.getString(columnIndex);
        selectedphoto = BitmapFactory.decodeFile(filePath);

        int updatedid=pref.getInt("updatedid",-1);
        if(updatedid==0) {
            image.setImageBitmap(selectedphoto);//here i setbitmap.
        }


        cursor.close();


    }

}

这是我的完整代码,请在我的代码中提出错误建议。

1 个答案:

答案 0 :(得分:0)

试试这个:

  1. 添加“image.setTag(R.drawable.bed1);”在for-loop中。

  2. 修改onLongClick():

    public boolean onLongClick(View v) {
        image = (ImageView) v;
        int updateid = v.getId();
        editor.putInt("updatedid",updateid).apply();
        int imgId = 0;
        if(v.getTag() != null) imgId = (Integer) v.getTag(); 
        if(imgId == R.drawable.bed1){
            image.setImageResource(R.drawable.hall);
            image.setTag(R.drawable.hall);
        }
        buttonGalleryOpen();//open the phone gallery
        return true;
    }
    
  3. 在OnActivityResult()中将“if(updatedid == 0){”更改为“if(updatedid&gt; = 0){”。

  4. 希望这有帮助!