我试图在ScrollView中创建一个包含多个View添加到LinearLayout的Activity.Those View是用LayoutInflater填充的布局文件,它们包含TextView和ViewPager(使用FragmentPagerAdapter)。问题是只有第一个ViewPager显示片段,而其他ViewPage只是空的。
MainActivity.class:
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout)findViewById(R.id.layout);
for(int i = 0;i<10;i++) {
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new FragmentRed());
pagerAdapter.addFragment(new FragmentYellow());
pagerAdapter.addFragment(new FragmentGreen());
View view = getLayoutInflater().inflate(R.layout.test_item, null);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
viewPager.setAdapter(pagerAdapter);
TextView textView = (TextView)view.findViewById(R.id.text_view);
textView.setText("SampleText " + i);
linearLayout.addView(view);
}
private class PagerAdapter extends FragmentPagerAdapter{
ArrayList<Fragment>fragments = new ArrayList<>();
public void addFragment(Fragment fragment){
fragments.add(fragment);
}
public PagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
}
这就是我在模拟器中得到的: https://i.stack.imgur.com/SKFYM.jpg
第一个ViewPager工作正常,我需要让其他人这样做。
test_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"></TextView>
<android.support.v4.view.ViewPager
android:id="@+id/view_pager"
android:layout_width="match_parent"
android:layout_height="100dp"></android.support.v4.view.ViewPager>>
</LinearLayout>
答案 0 :(得分:0)
很难解释,但我会尽力而为。
数组列表的工作方式与int,String,bools ...相同。如果声明数组列表,则声明它的方式指向相同的片段。 ArrayList可以包含对同一个确切对象的多个引用。
我认为你只需简单地解决问题:
for(int i = 0;i<10;i++) {
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new FragmentRed());
pagerAdapter.addFragment(new FragmentYellow());
pagerAdapter.addFragment(new FragmentGreen());
View view = getLayoutInflater().inflate(R.layout.test_item, null);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.view_pager);
viewPager.setAdapter(pagerAdapter);
TextView textView = (TextView)view.findViewById(R.id.text_view);
textView.setText("SampleText " + i);
linearLayout.addView(view);
}