2017-01-15 29 views
0

我一直在努力在Android Studio中创建ViewPager很长一段时间,但我刚刚意识到您可以使用预先配置的Activity自动创建一个。如何在Android Studio中编辑片段内容?

已经创造了一个Tabbed ActivityAction Bar TabsViewPager,我结束了两个XML布局:activity_main.xmlfragment_main.xml。但是,我不确定如何独立更改每个片段。无论何时我在fragment_main.xml中添加TextView,它都会显示在所有三个预定义的部分上。

如何更改一个部分而不影响其他两个?!

回答

-1

在FragmentPagerAdapter的getItem(int position)方法中,此行PlaceholderFragment.newInstance(position + 1)决定它返回哪个片段。 只有一种类型的片段,并返回的片段具有相同的布局,但在PlaceholderFragment你可以改变它根据位置的布局,例如:

/** 
* A placeholder fragment containing a simple view. 
*/ 
public static class PlaceholderFragment extends Fragment { 
    /** 
    * The fragment argument representing the section number for this 
    * fragment. 
    */ 
    private static final String ARG_SECTION_NUMBER = "section_number"; 

    public PlaceholderFragment() { 
    } 

    /** 
    * Returns a new instance of this fragment for the given section 
    * number. 
    */ 
    public static PlaceholderFragment newInstance(int sectionNumber) { 
     PlaceholderFragment fragment = new PlaceholderFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(ARG_SECTION_NUMBER, sectionNumber); 
     fragment.setArguments(args); 
     return fragment; 
    } 


    private int mPosition; 
    @Override 
    public void onCreate(@Nullable Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     mPosition = getArguments().getInt(ARG_SECTION_NUMBER); 

    } 
    private View mRootView; 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     switch (mPosition) { 
      case 0: 
       mRootView = inflater.inflate(R.layout.fragment_layout_0, container, false); 
       break; 
      case 1: 
       mRootView = inflater.inflate(R.layout.fragment_layout_1, container, false); 
       break; 
      case 2: 
       mRootView = inflater.inflate(R.layout.fragment_layout_2, container, false); 
       break; 
     } 
     TextView textView = (TextView) mRootView.findViewById(R.id.section_label); 
     textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER))); 
     return mRootView; 
    } 
} 
+0

请记住,所有的Java代码都必须在类中。 –

+0

对不起,你是对的。 –

+0

此外,这是最适当的做一个'PagerAdapter'和多个'Fragment'子类,每个布局一个。 –

0

你应该阅读Creating Swipe Views with Tabs。这将向您展示如何使用ViewPager创建制表符。特别是,您将需要一个PagerAdapter负责为每个选项卡创建正确的片段。