在GridView或简单的ListView中,我使用此代码将对象传递给新活动,并且它可以正常工作:
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Illusion i = (Illusion) parent.getItemAtPosition(position);
Intent intent = new Intent(IllusionsGridActivity.this, ViewIllusionActivity.class);
intent.putExtra("item", i);
startActivity(intent);
}
});
我试图在可扩展列表中对子对象执行相同操作,但它不起作用。它似乎只接受String值。所以这不起作用:
listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Illusion i = (Illusion) parent.getItemAtPosition(childPosition);
Intent intent = new Intent(IllusionsListActivity.this, ViewIllusionActivity.class);
intent.putExtra("item", i);
startActivity(intent);
return false;
}
});
有没有办法将整个对象传递给此方法中的新活动?
答案 0 :(得分:0)
尝试下一个代码:
listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
long packedPosition = ExpandableListView.getPackedPositionForChild(groupPosition, childPosition);
int flatPosition = parent.getFlatListPosition(packedPosition)
Illusion i = (Illusion) parent.getItemAtPosition(flatPosition);
Intent intent = new Intent(IllusionsListActivity.this, ViewIllusionActivity.class);
intent.putExtra("item", i);
startActivity(intent);
return false;
}
});
答案 1 :(得分:0)
尝试使用Parcable。
在第一个Activtiy中
Illusion i = (Illusion) parent.getItemAtPosition(position);
Intent in = new Intent(IllusionsGridActivity.this,ViewIllusionActivity.class);
in.putExtra("key", i);
startActivity(in);
在第二个Activtiy中
Intent intent = getIntent();
User usr = (User) intent.getParcelableExtra("key");
在幻觉课程中
import android.os.Parcel;
import android.os.Parcelable;
public class User implements Parcelable {
private long exampleValueLong;
private int exampleValueInt;
private String exampleValueString;
private boolean exampleValueBool;
public User(){}
// all getters and setters go here //...
@Override
public int describeContents() {
// ignore for now
return 0;
}
@Override
public void writeToParcel(Parcel pc, int flags) {
pc.writeLong(exampleValueLong);
pc.writeInt(exampleValueInt);
pc.writeString(exampleValueString);
pc.writeInt( exampleValueBool ? 1 :0 );
}
public static final Parcelable.Creator<User> CREATOR =
new Parcelable.Creator<Illusion>() {
public Illusion createFromParcel(Parcel pc) {
return new Illusion(pc);
}
public Illusion[] newArray(int size) {
return new Illusion[size];
}
};
public Illusion(Parcel pc){
exampleValueLong = pc.readLong();
exampleValueInt = pc.readInt();
exampleValueString = pc.readString();
exampleValueBool= ( pc.readInt() == 1 );
}
}