我已经为ListView
做了一个ContextMenu
,一切都很完美。但是,我不知道如何将所选项目发送到另一个活动?
我看了很多教程,但没有找到解决方案。
每个项目表示两列,其中包含两个使用 JSON 字符串解析的字符串(产品、价格)。
listViewProduse.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listViewProduse.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
final int checkedCount = listViewProduse.getCheckedItemCount();
mode.setTitle(checkedCount + " product selected");
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.main_context, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.add_id:
SparseBooleanArray selected = adapter.getSelectedIds();
String copyText="";
for (int i = (selected.size() - 1); i >= 0; i--){
if (selected.valueAt(i)){
VanzatorProduse selectedListItem = adapter.getItem(selected.keyAt(i));
}
}
mode.finish();
return true;
default:
return false;
}
}
您可以VanzatorProduse
实现Parcelable
接口,以便将其放入用于启动新活动的 Intent 中。如果你说这个类同时具有产品和价格,一个可能的实现可能如下所示:
public class VanzatorProduse implements Parcelable {
private String product;
private double price;
public VanzatorProduse(String product, double price) {
this.product = product;
this.price = price;
}
protected VanzatorProduse(Parcel in) {
product = in.readString();
}
public static final Creator<VanzatorProduse> CREATOR = new Creator<VanzatorProduse>() {
@Override
public VanzatorProduse createFromParcel(Parcel in) {
return new VanzatorProduse(in);
}
@Override
public VanzatorProduse[] newArray(int size) {
return new VanzatorProduse[size];
}
};
public String getProduct() {
return product;
}
public double getPrice() {
return price;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(product);
parcel.writeDouble(price);
}
}
然后在您的 onActionItemClicked 上,您只需声明VanzatorProduse
的ArrayList
并将其添加到Intent
中,如下所示:
ArrayList<VanzatorProduse> products = new ArrayList<>();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
VanzatorProduse selectedListItem = adapter.getItem(selected.keyAt(i));
products.add(selectedListItem);
}
}
Intent intent = new Intent(YourActivity.this, YourSecondActivity.class);
intent.putParcelableArrayListExtra("your_key", products);
startActivity(intent);
最后,在第二个活动中,从 onCreate
方法检索值,如下所示:
Intent intent = getIntent();
ArrayList<VanzatorProduse> products = intent.getParcelableArrayListExtra("your_key"); // same key used as before
希望对您有所帮助。