web-dev-qa-db-fra.com

Comment ajouter des éléments d'onglets de fragments dynamiques

Je veux ajouter des éléments d'onglet dynamiques. J'ai un fragment qui est FragmentOne et il a un TextView. J'essaie de créer FragmentOne dans foreach et d'ajouter des onglets. J'ai testé le code qui est dans setupViewPager mais cela ne fonctionne pas. Comment puis-je éditer TextView qui en fragments?

si je supprime ces lignes cela fonctionne mais le contenu de fragment indique toujours par défaut que = "TAB ONE". Je veux éditer tout TextView qui est dans des fragments qui ont été créés au moment de l'exécution;

View view = fView.getView();

TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
txtTabItemNumber.setText("TAB " + i);

DynamicTabsActivity.Java

public class DynamicTabsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_tabs);


        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }


    private void setupViewPager(ViewPager viewPager) {

        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        int count = 10;
        for (int i=0; i<count; i++){

            OneFragment fView = new OneFragment();
            View view = fView.getView();

            TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);
            txtTabItemNumber.setText("TAB " + i);
            adapter.addFrag(fView,"TAB " + i);
        }

        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFrag(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

activity_dynamic_tabs.xml

<Android.support.design.widget.CoordinatorLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:app="http://schemas.Android.com/apk/res-auto"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent">

    <Android.support.design.widget.AppBarLayout
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <Android.support.v7.widget.Toolbar
            Android:id="@+id/toolbar"
            Android:layout_width="match_parent"
            Android:layout_height="?attr/actionBarSize"
            Android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <Android.support.design.widget.TabLayout
            Android:id="@+id/tabs"
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </Android.support.design.widget.AppBarLayout>

    <Android.support.v4.view.ViewPager
        Android:id="@+id/viewpager"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</Android.support.design.widget.CoordinatorLayout>

OneFragment.Java

public class OneFragment extends Fragment{

    public OneFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false);

    }

}

fragment_one.xml

<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    tools:context="info.androidhive.materialtabs.fragments.OneFragment">

    <TextView
        Android:id="@+id/txtTabItemNumber"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:text="TAB ONE"
        Android:textSize="40dp"
        Android:textStyle="bold"
        Android:layout_centerInParent="true"/>

</RelativeLayout>

 enter image description here

6
Alexander

La disposition du fragment n'a pas été créée au point que vous appelez findViewById ci-dessous:

        OneFragment fView = new OneFragment();
        View view = fView.getView();

        TextView txtTabItemNumber = (TextView)view.findViewById(R.id.txtTabItemNumber);

Ce qui suit est plus généralement la façon dont cela est codé:

public static class OneFragment extends Fragment {
    private static final String ARG_SECTION_NUMBER = "section_number";
    private int sectionNumber;

    public OneFragment() {
    }

    public static OneFragment newInstance(int sectionNumber) {
        OneFragment fragment = new OneFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_one, container, false);

        sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER);
        TextView textView = (TextView) rootView.findViewById(R.id.txtTabItemNumber);
        textView.setText("TAB " + sectionNumber);
        return rootView;
    }
}

vous pouvez également vouloir déplacer la création de fragments vers l'adaptateur ... par exemple:

    public Fragment getItem(int position) {
        return OneFragment.newInstance(position + 1);
    }
7
John O'Reilly

Essaye ça,

  LinearLayout  main = new LinearLayout(this);
 main.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
    textView .setText("TAB " + i);
    main .addView(textView );
0
santosh kumar

Après avoir essayé longtemps ... je suis arrivé à la solution suivante: DynamicTabsActivity est mon activité principale, ressemble à ceci:

public class DynamicTabsActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;

    private int noOfTabs = 10;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_tabs);

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager(), noOfTabs);
        viewPager = findViewById(R.id.viewpager);
        viewPager.setAdapter(viewPagerAdapter);

        tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

}

Mon fragment ressemble à ceci:

public class DynamicFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";
    private int sectionNumber;


    public DynamicFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sectionNumber = getArguments() != null ? getArguments().getInt(ARG_SECTION_NUMBER) : 1;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_dynamic, container, false);

        TextView textView = view.findViewById(R.id.txtTabItemNumber);
        textView.setText("TAB " + sectionNumber);


        return  view;
    }

    public static DynamicFragment newInstance(int sectionNumber) {
        DynamicFragment fragment = new DynamicFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }
}

Ma classe ViewPager ressemble à ceci:

public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private int noOfItems;

    public ViewPagerAdapter(FragmentManager fm, int noOfItems) {
        super(fm);
        this.noOfItems = noOfItems;
    }

    @Override
    public Fragment getItem(int position) {
        return DynamicFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        return noOfItems;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "TAB "+(position+1);
    }
}

Layout DynamicTabsActivity:

<?xml version="1.0" encoding="utf-8"?>
<Android.support.constraint.ConstraintLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:app="http://schemas.Android.com/apk/res-auto"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    tools:context=".DynamicTabsActivity">

    <Android.support.design.widget.AppBarLayout
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <Android.support.v7.widget.Toolbar
            Android:id="@+id/toolbar"
            Android:layout_width="match_parent"
            Android:layout_height="?attr/actionBarSize"
            Android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <Android.support.design.widget.TabLayout
            Android:id="@+id/tabs"
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            app:tabMode="scrollable"/>
    </Android.support.design.widget.AppBarLayout>

    <Android.support.v4.view.ViewPager
        Android:id="@+id/viewpager"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</Android.support.constraint.ConstraintLayout>

Fragment layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    tools:context=".DynamicFragment">

    <TextView
        Android:id="@+id/txtTabItemNumber"
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:layout_centerInParent="true"
        Android:text="TAB ONE"
        Android:textSize="40dp"
        Android:textStyle="bold" />

</RelativeLayout>

J'espère que ça aide...

0
Ben