我正在尝试实现 parceable 以将数据传递到下一个屏幕,因此在我的家庭 Activity 中,我正在调用一堆方法(oncreate 等),现在我正在尝试从 oncreate 中进行的查询中获取并传递它在 onclick 上进入下一个屏幕,但是在 onclick 之前,我想通过告诉 parceable 来处理它来添加信息...但是我不确定如何将 onclick 中的信息传递到实现的新类中可共享...
这是我的代码尝试:(不确定我传递给额外的内容,android 网站上缺少文档)
@Override
public void onClick(View v) {
if (v == add_new_dictionary) {
Log.e("clicked add button", "adding the dictionary... ");
// no return true because it is void on intents
Intent add_new_dictionary_intent = new Intent(MainActivity.this,
add_new_dictionary.class);
startActivity(add_new_dictionary_intent);
} else {
// used to get tag for dictionary
Object tag = v.getTag();
//call parceable
SendIdOfDictionary(tag);
// start new intent based on the tag -
Intent new_dictionary_view = new Intent(MainActivity.this,
dictionary_view.class);
new_dictionary_view.putExtra("d_id", WhatAmISupposeToPassInHere);
startActivity(new_dictionary_view);
}
// parceable is faster than serialization - create class to implement it
}
private void SendIdOfDictionary(Object tag) {
class ParceDictionaryData implements Parcelable {
private String tag;
/* everything below here is for implementing Parcelable */
// 99.9% of the time you can just ignore this
public int describeContents() {
return 0;
}
// write your object's data to the passed-in Parcel
public void writeToParcel(Parcel out, int flags) {
out.writeString(tag);
}
// this is used to regenerate your object. All Parcelables must have
// a CREATOR that implements these two methods
public final Parcelable.Creator<ParceDictionaryData> CREATOR = new Parcelable.Creator<ParceDictionaryData>() {
public ParceDictionaryData createFromParcel(Parcel in) {
return new ParceDictionaryData(in);
}
public ParceDictionaryData[] newArray(int size) {
return new ParceDictionaryData[size];
}
};
// example constructor that takes a Parcel and gives you an object
// populated with it's values
private ParceDictionaryData(Parcel in) {
tag = in.readString();
}
}
最佳答案
使用 bundle ,此处不需要 Parceable。
将其添加到启动第二个 Activity 的 Intent 中:
Intent i = new Intent();
i.putExtra("tag", yourTag);
然后获取它
getIntent().getExtras().getString("tag");
关于java - 如何将 id 传递到 Parcelable 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21499084/