我怎样才能创建一个标签式活动的每个选项卡的用户界面?创建一个、用户界面、选项卡、标签

2023-09-04 09:14:12 作者:为君战

我在学习开发的机器人,但我不知道如何创建UI的一个片段。 我创建了一个新的活动,在创建过程中,我选择了导航类型选项卡+刷卡。 现在我有一个布局的XML,我不能修改通过所见即所得的界面,如果我 - 对于示例 - 使用Java它在每一个标签视图创建它的类文件的一个按钮控件。

I'm learning developing for android but i don't know how to create the UI for a Fragment. I created a new activity and during the creation process I selected the navigation type "Tabs + Swipe". Now i have a layout xml which i can't modify using the WYSIWYG interface and if i -for example- create a button widget using java in the class file it creates it in every "tab view".

基本上,我想创建不同的界面为每个标签(片段)。

I basically want to create different interfaces for every tab (fragment).

感谢您

推荐答案

在刚创建活动,你可以找到内部类 SectionsPagerAdapter 。看看这个方法:

In just created Activity you can find inner class SectionsPagerAdapter. Look at this method:

@Override
public Fragment getItem(int i) {
    Fragment fragment = new DummySectionFragment();
    Bundle args = new Bundle();
    args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
    fragment.setArguments(args);
    return fragment;
}

这方法对于每个标签返回DummySectionFragment的情况下,只有不同的包。如果你想创建一个具有每个选项卡,你应该检查变量的值,并根据该值来创建适当的片段不同的看法片段。例如:

This method for every tab returns instance of DummySectionFragment with only different bundles. If you want to create fragments with different views for every tab you should check value of i variable and according to this value create proper fragment. For example:

@Override
public Fragment getItem(int i) {
    Fragment fragment; 
    switch(i){
    case 0:
         fragment = new MyFragment1();
         break;
    case 1:
         fragment = new MyFragment2();
         break;
    case 3:
         fragment = new MyFragment3();
         break;
    default:
         throw new IllegalArgumentException("Invalid section number");
    }

    //set args if necessary
    Bundle args = new Bundle();
    args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
    fragment.setArguments(args);

    return fragment;
}

而不是 DummySectionFragment 类的创建三个类别:MyFragment1,MyFragment2,MyFragment2并为每个,里面的方法 onCreateView 创建或者夸大观点,例如:

Instead of DummySectionFragment class create three classes: MyFragment1, MyFragment2, MyFragment2 and for each, inside method onCreateView create or inflate view, for example:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.my_fragment1.xml, null);
    return v;

}

在哪里R.layout.my_fragment1.xml是你MyFragment1片段布局。

Where R.layout.my_fragment1.xml is layout of your MyFragment1 fragment.