如何使用 2 个活动和自定义适配器将图库中的图片或用相机拍摄的图片动态添加到 ListView 中

How to add picture from gallery or taken with camera into a ListView dinamically using 2 activities and a custom adapter

我有两个 activity:

  1. 首先activity:MyCollectionActivity

在这个 activity 中,我有一个用于标题的 TextView,一个用于显示我的邮票列表的 ListView 和一个 FloatingButtonAction。

当我单击 FloatingButtonAction 时,我想开始我正在谈论的第二个 activity:InsertStampActivity。

  1. 第二个activity:InsertStampActivity

InsertStampActivity,其中我有 3 个 EditText(插入国家/地区、值、年份)、一个 ImageButton 和一个空的 ImageView(用于插入的图像)。当我单击 ImageButton 时,它将弹出一个带有 3 个按钮的 AlertDialogBox:按钮 - 来自画廊,按钮 - 拍摄照片或按钮 - 退出。

当我点击 FROM GALLERY 时,我想从我的 phone 的图库中 select 一张图片,当我点击 TAKE PHOTO 打开 phone 的相机拍摄时照片,当我单击“退出”时,return 到 MyCollectionActivity。

为此,我想使用 CustomAdapter。

---我的问题是如何管理插入的图片。---

我的 CLASS Timbru(意思是印记):

public class Timbru implements Parcelable {

private Integer year;
private String country;
private Float value;
private String imagePath;

public Timbru(int year, String country, float value, String imagePath) {
    this.year = year;
    this.country = country;
    this.value = value;
    this.imagePath = imagePath;
}

public Timbru() {
}

public String getImagePath() {
    return imagePath;
}

public void setImagePath(String imagePath) {
    this.imagePath = imagePath;
}

public Integer getYear() {
    return year;
}

public void setYear(Integer year) {
    this.year = year;
}

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public Float getValue() {
    return value;
}

public void setValue(Float value) {
    this.value = value;
}

@Override
public String toString() {
    return "Timbru{" +
            "year=" + year +
            ", country='" + country + '\'' +
            ", value=" + value +
            ", imagePath='" + imagePath + '\'' +
            '}';
}

public Timbru(Parcel in) {
    this.year = in.readInt();
    this.country = in.readString();
    this.value = in.readFloat();
}

public static Parcelable.Creator<Timbru> CREATOR = new Creator<Timbru>() {
    @Override
    public Timbru createFromParcel(Parcel parcel) {
        return new Timbru(parcel);
    }

    @Override
    public Timbru[] newArray(int i) {
        return new Timbru[i];
    }
};

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeInt(year);
    parcel.writeString(country);
    parcel.writeFloat(value);
    }  
}

这是一个 class 用于保存列表:

public class ListaTimbru {

private static ArrayList<Timbru> timbre = new ArrayList<>();

public static ArrayList<Timbru> getTimbre() {
    return timbre;
}

public ListaTimbru() {

     }
}

这是 TimbruAdapter class:

public class TimbruAdapter extends ArrayAdapter {

private int resource;
private List<Timbru> objects;
private LayoutInflater inflater;


public TimbruAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List objects, LayoutInflater inflater) {
    super(context, resource, objects);
    this.inflater = inflater;
    this.resource = resource;
    this.objects = objects;
}

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

    View row = inflater.inflate(this.resource, parent, false);

    TextView tvYear = (TextView) row.findViewById(R.id.tv_year_rowLayout2);
    TextView tvCountry = (TextView) row.findViewById(R.id.tv_country_rowLayout2);
    TextView tvValue = (TextView) row.findViewById(R.id.tv_value_rowLayout2);

    Timbru timbru = objects.get(position);

    tvCountry.setText(timbru != null && timbru.getCountry() != null ? timbru.getCountry() : "");
    tvYear.setText(timbru != null && timbru.getYear() != null ? timbru.getYear().toString() : "");
    tvValue.setText(timbru != null && timbru.getValue() != null ? timbru.getValue().toString() : "");

    return row;
    }
 }

这是 MyCollectionActivity:

public class MyColectionActivity extends AppCompatActivity {

    FloatingActionButton fltBtn_insert;
    ListView listViewStamps;
    List<String> listStamps = new ArrayList<>();
    List<Timbru> listStamps2 = new ArrayList<>();

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

    fltBtn_insert = (FloatingActionButton) 
    findViewById(R.id.flBtn_insertNewStamp_myCollection);
    listViewStamps = (ListView) 
    findViewById(R.id.lv_stampList_myCollection);

    TimbruAdapter adapter = new TimbruAdapter(getApplicationContext(), R.layout.row_layout2, ListaTimbru.getTimbre(), getLayoutInflater());
    listViewStamps.setAdapter(adapter);

    fltBtn_insert.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), InsertStampActivity.class);
            startActivityForResult(intent, Constants.ADD_STAMP_REQUEST_CODE);
        }
    });
}

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

    if (requestCode == Constants.ADD_STAMP_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
        Timbru result = data.getParcelableExtra(Constants.ADD_STAMP_KEY);
        if (result != null) {
            ListaTimbru.getTimbre().add(result);
            TimbruAdapter currentAdapter = (TimbruAdapter) listViewStamps.getAdapter();
            currentAdapter.notifyDataSetChanged();
        }
    }
}

这是 InsertStampActivity:

public class InsertStampActivity extends AppCompatActivity {

EditText et_year;
EditText et_country;
EditText et_value;
Intent intent;
Button insertStamp;
ImageView poza_timbru;
Uri imageUri;
static final int PICK_IMAGE_REQUEST=1;
static final int REQUEST_IMAGE_TAKEN=2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_insert_stamp);
    initializareComponente();
    intent = getIntent();
}

private void initializareComponente() {
    et_year = (EditText) findViewById(R.id.et_year_insertStamp);
    et_country = (EditText) findViewById(R.id.et_country_insertStamp);
    et_value = (EditText) findViewById(R.id.et_value_insertStamp);
    poza_timbru = (ImageView) findViewById(R.id.imgView_stampAdded_insertStamp);

    insertStamp = (Button) findViewById(R.id.btn_insertStamp);

    insertStamp.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (validation()) {
                Timbru timbru = createTimbruFromComponents();
                if (timbru != null) {
                    intent.putExtra(ADD_STAMP_KEY, timbru);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        }
    });
}

private Timbru createTimbruFromComponents() {
    Integer year = Integer.parseInt(et_year.getText().toString());
    String country = et_country.getText().toString();
    Float value = Float.parseFloat(et_value.getText().toString());


    Uri selectedImage=intent.getData();
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
    int columnIndex = 0;
    String picturePath = null;
    if (cursor != null) {
        cursor.moveToFirst();
        columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        picturePath = cursor.getString(columnIndex);
        cursor.close();
    }
    return new Timbru(year, country, value,picturePath);
}

private boolean validation() {
    //only for EditTexts
    if (et_year.getText() == null || et_year.getText().toString().trim().isEmpty() || et_year.getText().toString().length() < 4) {
        Toast.makeText(getApplicationContext(), "Year is not valid", Toast.LENGTH_SHORT).show();
    }
    if (et_country.getText() == null || et_country.getText().toString().trim().isEmpty()) {
        Toast.makeText(getApplicationContext(), "Country is not valid", Toast.LENGTH_SHORT).show();
    }
    if (et_value.getText() == null || et_value.getText().toString().trim().isEmpty()) {
        Toast.makeText(getApplicationContext(), "Value is not valid", Toast.LENGTH_SHORT).show();
    }
    return true;
}

public void imgBtn_insertImagine(View view) {

    //DIALOG BOX
    final Dialog dialog = new Dialog(getApplicationContext());
    dialog.setContentView(R.layout.custom_dialog_box);
    dialog.setTitle("PICK ONE");
    Button exit = (Button) findViewById(R.id.btnExit_dialogBox);
    exit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dialog.dismiss();
        }
    });
    dialog.findViewById(R.id.btnForGallery_dialogBox).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openGallery();
        }
    });

    dialog.findViewById(R.id.btnTakePhoto_dialogBox).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            openCamera();
        }
    });

    dialog.show();
}

public void openCamera() {
    Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (intentCamera.resolveActivity(getPackageManager()) != null) {
        String fileName = "temp.jpg";
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, fileName);
        imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, REQUEST_IMAGE_TAKEN);
    }
}

public void openGallery() {
    Intent intentGallery = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    intent.setType("image/*"); //arata doar imagini, nu si video sau altceva
    startActivityForResult(intentGallery, PICK_IMAGE_REQUEST);
}

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

    switch (requestCode) {
        case PICK_IMAGE_REQUEST:
            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                int columnIndex = 0;
                String picturePath = null;
                if (cursor != null) {
                    cursor.moveToFirst();
                    columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    picturePath = cursor.getString(columnIndex);
                    cursor.close();
                }
                Timbru timbru = new Timbru();
                timbru.setCountry("Madagascar");
                timbru.setValue(20.4f);
                timbru.setImagePath(picturePath);
                timbru.setYear(1200);
                ListaTimbru.getTimbre().add(timbru);
            }
             break;
        case REQUEST_IMAGE_TAKEN:
            if (requestCode == REQUEST_IMAGE_TAKEN && resultCode == RESULT_OK) {
                String[] projection = {MediaStore.Images.Media.DATA};
                Cursor cursor = managedQuery(imageUri, projection, null, null, null);
                int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                String picturePath = cursor.getString(column_index_data);
                Timbru timbru = new Timbru();
                timbru.setCountry("Australia");
                timbru.setValue(55.5f);
                timbru.setImagePath(picturePath);
                timbru.setYear(1800);
                ListaTimbru.getTimbre().add(timbru);
            }
            break;
        }
    }
}

在同一个 Activity(InsertStampActivity) 中,您可以使用此代码将相机和图库中的图像显示到图像视图

case REQUEST_IMAGE_TAKEN:
 if (requestCode == REQUEST_IMAGE_TAKEN && resultCode == RESULT_OK) 
 {
   Bitmap photo = (Bitmap) data.getExtras().get("data"); 
   poza_timbru.setImageBitmap(photo); //poza_timbru is your imageview.
 }
case PICK_IMAGE_REQUEST:
 if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) 
 {

   Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
   poza_timbru.setImageBitmap(thumbnail); //poza_timbru is your imageview.
 }

然后在适配器 class 视图中添加一个图像视图 R.Layout。row_layout2 将您的数据传递给适配器 class 然后在列表视图中显示它。

希望对您有所帮助..!