I have fragment where I get the string in List and send it as Bundle to the activity. For Example I get a string and and send it to an activity by following way:
public class ViewPagerAdapter extends FragmentStatePagerAdapter
{
private CharSequence contentTitle[];
public ViewPagerAdapter(Response<album> response)
{
List<String> listcontentTitle = new ArrayList<>();
List<List<String>> latest_list = new ArrayList<>();
List<String> latestdate = new ArrayList<>();
List<String> latestcomment = new ArrayList<>();
for (int i = 0; i < 5; i++)
{
listcontentTitle.add(String.valueOf(response.body().getcontent().get(i).getcontentTitle()));
latestdate.add(String.valueOf(response.body().getcontent().get(i).getcontentdate()));
latestcomment.add(String.valueOf(response.body().getcontent().get(i).getcontentcmnt()));
}
latest_list.add(latestdate);
latest_list.add(latestcomment);
this.contentTitle = listcontentTitle.toArray(new CharSequence[listcontentTitle.size()]);
// (1) access latest_list with this keyword
}
@Override
public Fragment getItem(int position)
{
Fragment Detail=new Detail(mContext);
Bundle bundle= new Bundle();
bundle.putString("content_title",contentTitle[position].toString());
// (2) pass the latest list in bundle
Detail.setArguments(bundle);
return Detail;
}
}
Now what should be my (1) and (2) in order to access latest_list and pass it in bundle?
Mick Ashton
1) You cannot use this
here. Set it as a private right above the method, like this:
public class ViewPagerAdapter extends FragmentStatePagerAdapter
{
private CharSequence contentTitle[];
private List<List<String>> latestList; // This let's you use latestList outside of this ViewPagerAdapter class.
public ViewPagerAdapter(Response<album> response)
{
List<String> listcontentTitle = new ArrayList<>();
List<List<String>> latest_list = new ArrayList<>();
List<String> latestdate = new ArrayList<>();
List<String> latestcomment = new ArrayList<>();
for (int i = 0; i < 5; i++)
{
listcontentTitle.add(String.valueOf(response.body().getcontent().get(i).getcontentTitle()));
latestdate.add(String.valueOf(response.body().getcontent().get(i).getcontentdate()));
latestcomment.add(String.valueOf(response.body().getcontent().get(i).getcontentcmnt()));
}
latest_list.add(latestdate);
latest_list.add(latestcomment);
contentTitle = listcontentTitle.toArray(new CharSequence[listcontentTitle.size()]);
lastestList = lastest_list;
}
public List<List<String>> getLatestList(){
return latestList;
}
You can now use latestList
in another class like this:
ViewPageAdapter viewpage = new ViewPageAdapter(response);
List<List<String>> latest_list = viewpage.getLatestList();
For passing a list using bundles, look at this answer: https://stackoverflow.com/a/28197436/4561008
You'll need to use implements Parcelable
in your ViewPageAdapter declaration.
来源:https://stackoverflow.com/questions/42137823/how-to-get-listliststring-with-this-keyword