将模型对象传递给另一个Activity

时间:2015-09-15 19:14:58

标签: android android-layout android-fragments android-intent android-activity

我有RecyclerView利用Recycler Adapter输出列表布局,如下所示:

http://i.imgur.com/ORkXXTb.png

我需要将下面的模型附加到每个列表项中,这样,如果用户单击列表项中的任何元素(如圆圈或两个TextView中的一个),它会将模型对象传递给下一个Activity

以下是User型号:

public class User {

    private String id;
    private String username;
    private String displayName;
    private Object deletedAt;
    private Statistic stat;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username= username;
    }

    public String getDisplayName() {
        return displayName;
    }

    public void setDisplayName(String displayName) {
        this.displayName = displayName;
    }

    public Object getDeletedAt() {
        return deletedAt;
    }

    public void setDeletedAt(Object deletedAt) {
        this.deletedAt = deletedAt;
    }

    public Statistic getStat() {
        return stat;
    }

    public void setStat(Statistic stat) {
        this.stat = stat;
    }

}

以下是每个列表项(user_layout.xml)的布局:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/user_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/white">

            <ImageView
                android:id="@+id/avatar"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_alignParentLeft="true"
                android:background="@drawable/avatar" />


            <TextView
                android:id="@+id/display_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignTop="@+id/avatar"
                android:layout_toRightOf="@+id/avatar"
                />

            <TextView
                android:id="@+id/username"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/display_name"
                />

        </RelativeLayout>

    </LinearLayout>

</LinearLayout>

以下是UserRecyclerAdapter用于夸大上述布局的内容:

public class UserRecyclerAdapter extends RecyclerView.Adapter<UserRecyclerAdapter.ViewHolder> {

    private Context context;
    private List<User> mDataset;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView avatar;
        public TextView displayName;
        public TextView username;

        public ViewHolder(LinearLayout view) {
            super(view);

            avatar = (ImageView) view.findViewById(R.id.avatar);
            displayName = (TextView) view.findViewById(R.id.display_name);
            username = (TextView) view.findViewById(R.id.username);
        }
    }

    public UserRecyclerAdapter(Context context, List<User> myDataset) {
        this.context = context;
        this.mDataset = myDataset;
    }

    @Override
    public UserRecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_layout, parent, false);
        ViewHolder vh = new ViewHolder((LinearLayout) view);

        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        User userItem = mDataset.get(position);

        holder.displayName.setText(userItem.getDisplayName());
        holder.username.setText(userItem.getUsername());
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

}

所以我的问题是,如何将User模型对象附加到每个列表项,以便在单击某个元素(如圆圈或两个TextView)时,它将模型对象传递给下一个{{ 1}}?

感谢。

3 个答案:

答案 0 :(得分:5)

implements Serializable班级中的{p> User,如User implements Serializable

通过Bundle传递可序列化的类,如

User userItem = mDataset.get(position);

Intent yourIntent = new Intent(this, YourNextActivity.class);
Bundle b = new Bundle();
b.putSerializable("user", userItem);
yourIntent.putExtras(b); //pass bundle to your intent
startActivity(yourIntent);

并获取

Intent i = getIntent();
Bundle bundle = i.getExtras();
User user = (User) bundle.getSerializable("user");

答案 1 :(得分:3)

让用户实现Parceable界面。

如果您使用的是Android Studio,那么有一个很棒的插件可以帮助您使用名为&#34; Android Parcelable code generator&#34;的插件。使用该插件,您可以自动生成所有必需的代码,但基本思路如下:

你需要一个空的构造函数:

public User() {}

然后实现接口方法:

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(id);
    dest.writeString(userName);
    dest.writeString(displayName);
    ...
    // Any object to be added to dest must implement Parceable in its turn
    // Please note that Lists and Serializable objects are already supported out of the box
}

public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {

    @Override
    public EventFrame createFromParcel(Parcel source) {
        return new User(source);
    }

    @Override
    public EventFrame[] newArray(int size) {
        return new User[size];
    }
};

private EventFrame(Parcel source) {
    id = source.readString();
    accessToken = source.readString();
    displayName = source.readString();
    ...
}

之后,在为下一个活动创建意图时,只需执行以下操作:

Intent yourIntent = new Intent(this, DestinyClass.class);
yourIntent.putExtra("user_identifier", user);

答案 2 :(得分:2)

使用this library

compile(group: 'org.apache.cxf', name: 'cxf-rt-frontend-jaxrs', version:'2.7.17')

+--- org.apache.cxf:cxf-rt-frontend-jaxrs:2.7.17
|    +--- org.apache.cxf:cxf-api:2.7.17
|    |    +--- org.codehaus.woodstox:woodstox-core-asl:4.4.1 (*)
|    |    +--- org.apache.ws.xmlschema:xmlschema-core:2.1.0 -> 2.2.1
|    |    +--- org.apache.geronimo.specs:geronimo-javamail_1.4_spec:1.7.1
|    |    \--- wsdl4j:wsdl4j:1.6.3
|    +--- org.apache.cxf:cxf-rt-core:2.7.17
|    |    +--- org.apache.cxf:cxf-api:2.7.17 (*)
|    |    +--- com.sun.xml.bind:jaxb-impl:2.1.13 -> 2.2.11
|    |    \--- org.apache.ws.xmlschema:xmlschema-core:2.1.0 -> 2.2.1
|    +--- javax.ws.rs:javax.ws.rs-api:2.0-m10
|    +--- org.apache.cxf:cxf-rt-bindings-xml:2.7.17
|    |    \--- org.apache.cxf:cxf-api:2.7.17 (*)
|    \--- org.apache.cxf:cxf-rt-transports-http:2.7.17
|         +--- org.apache.cxf:cxf-api:2.7.17 (*)
|         \--- org.apache.cxf:cxf-rt-core:2.7.17 (*)

java.lang.NoSuchMethodError: org.apache.cxf.common.util.ClassHelper.getRealClass(Lorg/apache/cxf/Bus;Ljava/lang/Object;)Ljava/lang/Class;
at org.apache.cxf.jaxrs.provider.ProviderFactory.setCommonProviders(ProviderFactory.java:499)
at org.apache.cxf.jaxrs.client.ClientProviderFactory.setProviders(ClientProviderFactory.java:85)
at org.apache.cxf.jaxrs.provider.ProviderFactory.initBaseFactory(ProviderFactory.java:137)
at org.apache.cxf.jaxrs.client.ClientProviderFactory.initBaseFactory(ClientProviderFactory.java:77)
at org.apache.cxf.jaxrs.client.ClientProviderFactory.createInstance(ClientProviderFactory.java:56)
at org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean.initClient(JAXRSClientFactoryBean.java:377)
at org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean.createWebClient(JAXRSClientFactoryBean.java:225)
at org.apache.cxf.jaxrs.client.WebClient.create(WebClient.java:113)

更新

@Parcel
public class User {
    public User() {}
    // You can keep all the members private with @Parcel(Serialization.BEAN)
    public String id;
    public String username;
    public String displayName;
    public Object deletedAt;
    public Statistic stat; // Needs to be @Parcel annotated as well
}

ActivityA.java
void openActivityB() {
    Intent intent = new Intent(this, ActivityB.class);
    intent.putExtra("user", Parcels.wrap(user));
    startActivity(intent);
}

ActivityB.java
void receive() {
    User user = Parcels.unwrap(getIntent().getParcelableExtra("user"));
}