android – 如何通过FragmentPagerAdapter将变量传递给片段?
作者:互联网
我是一个机器人初学者,试图学习,这是我的第一个问题,所以请原谅我,如果问题太简单,请告诉我,如果我正在使用论坛不正确.
我有一个FragmentActivity使用包含viewpager的布局;该活动创建一个MyFragmentPagerAdapter实例,它创建了几个MyFragment实例.所有都是support.v4版本.
我试图找到一种方法来传递一个整数值(表示用户之前做出的选择,实际上可能是一个可绘制的id)到片段.我正在使用意图通过它
对于这个活动,我知道我可以使用bundle将FragmentPagerAdapter中的值传递给片段,但是我找不到从活动到FragmentPagerAdapter的方法.我尝试了几种方法,包括更改构造函数但无法使其工作.
我错过了一些简单的事吗?做这个的最好方式是什么?
活动
public class SecondActivity extends FragmentActivity {
private MyIntegerAdapter1 mAdapter1;
private ViewPager mPager1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_layout);
mAdapter1 = new MyIntegerAdapter1(getSupportFragmentManager());
mPager1 = (ViewPager) findViewById(R.id.pager1);
mPager1.setAdapter(mAdapter1);
FragmentPagerAdapter
public class MyIntegerAdapter1 extends FragmentPagerAdapter {
public MyIntegerAdapter1(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Fragment f1 = new IntegerFragment();
Bundle args1 = new Bundle();
args1.putInt("param", R.drawable.image1);
args1.putInt("number", 1);
f1.setArguments(args1);
return f1;
etc
分段
public class IntegerFragment extends Fragment {
private int imageResourceId;
private int numberSelected;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
imageResourceId = getArguments().getInt("param");
numberSelected = getArguments().getInt("number");
解决方法:
我从最初的Google Samples中提取了这个.
分段:
public class IntegerFragment extends Fragment {
int imageResourceId;
int numberSelected;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//change to avoid orientation crash
imageResourceId = getArguments().getInt("param");
numberSelected = getArguments().getInt("number");
}
public static Fragment newInstance(int imageResourceId, int numberSelected) {
IntegerFragment f = new IntegerFragment();
f.imageResourceId = imageResourceId;
f.numberSelected = numberSelected;
return f;
}
FragmentPagerAdapter
public class MyIntegerAdapter1 extends FragmentPagerAdapter {
private Fragment[] fragments;
public MyIntegerAdapter1(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
if (content != null && position < content.length) {
if (fragments[position] == null) {
fragments[position] = IntegerFragment.newInstance(R.drawable.image1, 1);
}
return fragments[position % fragments.length];
}
return null;
etc
标签:android,android-fragments,android-viewpager,fragmentpageradapter 来源: https://codeday.me/bug/20191005/1855460.html