如何通过qazxswpoi从另一个活动中获得自定义ArrayList
?例如,我在活动A中有这个Intent
:
ArrayList
我如何在活动B中获得此列表?
要理解的第一部分是使用ArrayList<Song> songs;
对象将活动A中的信息传递给活动B,在其中可以放置“extras”。可以在Intent
中找到的完整列表可以在这里找到:Intent
(参见各种https://developer.android.com/reference/android/content/Intent.html方法,以及下面的putExtra()
方法)。
既然你试图通过putFooExtra()
,你有两个选择。
第一个,也是最好的,是使用ArrayList<Song>
。要使用它,putParcelableArrayListExtra()
类必须实现Song
接口。如果你控制Parcelable
的源代码,实现Song
相对容易。您的代码可能如下所示:
Parcelable
第二是使用Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putParcelableArrayListExtra("songs", songs);
。当您不控制version of putExtra()
that accepts a Serializable
object的源代码时,您应该只使用此选项,因此无法实现Song
。您的代码可能如下所示:
Parcelable
这就是你如何将数据放入活动A中的Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putSerializableExtra("songs", songs);
中。如何从活动B中的Intent
中获取数据?
这取决于您在上面选择的选项。如果您选择第一个,您将编写如下所示的内容:
Intent
如果您选择第二个,您将编写如下内容:
List<Song> mySongs = getIntent().getParcelableArrayListExtra("songs");
第一种技术的优点是它更快(就应用程序的用户性能而言)并且它占用的空间更少(就您传递的数据大小而言)。
Misam正在发送歌曲列表,所以它不能使用普通的List<Song> mySongs = (List<Song>) getIntent().getSerializableExtra("songs");
。相反,Song类必须实现Parcelable接口。我已经解释了如何在putStringArrayList()
后实现Parcelable painless。
实现Parcelable接口后,只需按照Uddhavs的回答进行小修改即可:
here
我希望这可以帮助你。
1.你的Song类应该实现Parcelable Class
// First activity, adding to bundle
bundle.putParcelableArrayListExtra("myArrayListKey", arrayList);
// Second activity, reading from bundle
ArrayList<Song> list = getIntent().getParcelableArrayListExtra("myArrayListKey");
2.将你的arraylist放到putParcelableArrayListExtra()
public class Song implements Parcelable {
//Your setter and getter methods
}
3.在活动中
public class ActivityA extends AppCompatActivity {
ArrayList<Song> songs;
@Override
protected void onCreate(Bundle savedInstanceState) {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), ActivityB.class)
.putParcelableArrayListExtra("songs", (ArrayList<? extends Parcelable>) songs));
}
});
}
请注意,bundle是Android系统中用于组件间通信的关键组件之一。您需要考虑的是如何使用将数组放入该包中。
发送方(活动A)
public class ActivityB extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
final ArrayList<Song> songs = intent.getParcelableArrayListExtra("songs");
//Check the value in the console
buttonCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for (Song value : songs) {
System.out.println(value.getTitle());
}
}
});
}
/ *注意:你必须使用writeToParcel()方法来编写Song对象的不同参数值* /
Intent intent1 = new Intent(MainActivity.this, NextActivity.class);
Bundle bundle = new Bundle();
Parcelable[] arrayList = new Parcelable[10];
接收方(活动B)
/* you can add more string values in your arrayList */
bundle.putParcelableArray("myParcelableArray", arrayList);
intent1.putExtra("myBundle", bundle);
startActivity(intent1);