user6008330
user6008330

Reputation:

How to get current Fragment name in viewpager?

Explaining, I use the viewpager class for 2 activities. When you click on an item in the ActivityMainTab list, it is taken to another activity (ActivityAtTab), it also uses the same viewpager class as the previous one to generate its tabs and fragments.

I need to know if the Conduit fragment is what is on the screen, so that under the conditions I will show below, I can go to the correct method and continue the flow.

Below the codes:

ActivityAtTab, this method checks which fragment is on the screen, so that the matches variable goes to the correct showResults. In the case of mFragmentConduit, I can not tell if it is on the screen because it comes from viewPager. ActivityAtTab

@Override
public void onResults(Bundle results) {

    //inicializando as variáveis de fragments
    av = (FragmentAv) getSupportFragmentManager().findFragmentByTag(getString(R.string.tag_fragment_av));
    rec = (FragmentRec) getSupportFragmentManager().findFragmentByTag(getString(R.string.tag_fragment_rec));
    ex = (FragmentEx) getSupportFragmentManager().findFragmentByTag(getString(R.string.tag_fragment_ex));
    enc = (FragmentEnc) getSupportFragmentManager().findFragmentByTag(getString(R.string.tag_fragment_enc));
    atest = (FragmentAtest) getSupportFragmentManager().findFragmentByTag(getString(R.string.tag_fragment_atest));
    dig = (FragmentDiag) getSupportFragmentManager().findFragmentByTag(getString(R.string.tag_fragment_diag));
    mFragmentConduit = (FragmentConduit) getSupportFragmentManager().findFragmentByTag(getString(R.string.tag_fragment_conduit));

    //pegando a lista de comandos
    ArrayList<String> matches = results
            .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

    //Verifica qual fragment está chamando a interface
    //e passa o valor da string para que seja implementada nos respectivos campos.
    try {
        if (av != null && av instanceof ResultFragmentsConduit) {
            resultFragmentsConduit = av;
            resultFragmentsConduit.showCondutaResults(matches);
        } else if (rec != null && rec instanceof ResultFragmentsConduit) {
            ResultFragmentsConduit = rec;
            ResultFragmentsConduit.showCondutaResults(matches);
        } else if (ex != null && ex instanceof ResultFragmentsConduit) {
            ResultFragmentsConduit = ex;
            ResultFragmentsConduit.showCondutaResults(matches);
        } else if (enc != null && enc instanceof ResultFragmentsConduit) {
            ResultFragmentsConduit = enc;
            ResultFragmentsConduit.showCondutaResults(matches);
        } else if (at != null && at instanceof ResultFragmentsConduit) {
            ResultFragmentsConduit = at;
            ResultFragmentsConduit.showCondutaResults(matches);
        } else if (dig != null && dig instanceof ResultFragmentsConduit) {
            ResultFragmentsConduit = dig;
            ResultFragmentsConduit.showCondutaResults(matches);
        } else if (mFragmentConduit != null && mFragmentConduit.isVisible() ){ //ALWAYS NULL!!!!!!!!!
            showResultsConduit(matches);
        }
    } catch (Exception e) {
        e.getStackTrace();
        Log.e(TAG_TABATENDIMENTO, e.getMessage());
    }
}

ActivityAtTab's onCreate method, where fragment is submitted for construction in viewPager:

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

        //TODO FRAGMENTOS
        mFragmentsArrayList = new ArrayList<>();
        mFragmentsArrayList.add(mFragmentConduit = new FragmentConduit());
        mFragmentsArrayList.add(new FragmentHistorico());

        stringArrayListTitleFragment = new ArrayList<>();
        stringArrayListTitleFragment.add(getString(R.string.fragment_conduit));
        stringArrayListTitleFragment.add(getString(R.string.fragment_historico));

        mCustomTabLayout = new CustomTabLayout(this, mFragmentsArrayList, stringArrayListTitleFragment);

        requestPermission();
    }

ViewPager:

public class CustomTabLayout {

    public AppCompatActivity mAppCompatActivity;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private PagerAdapter adapter;
    private ArrayList<Fragment> mFragmentArrayList;
    private ArrayList<String> mFragmentArrayListTitle;

    public CustomTabLayout(AppCompatActivity appCompatActivity, ArrayList<Fragment> fragments, ArrayList<String> stringArrayListFragments) {

        mAppCompatActivity = appCompatActivity;

        mFragmentArrayList = fragments;
        mFragmentArrayListTitle = stringArrayListFragments;

        viewPager = mAppCompatActivity.findViewById(R.id.viewpager);

        tabLayout = mAppCompatActivity.findViewById(R.id.tabs);

        createViewPager(viewPager);

        tabLayout.setupWithViewPager(viewPager);

        tabLayout.setOnTabSelectedListener(adapter);

        createTabIcons();
    }

    private void createViewPager(ViewPager viewPager) {

        adapter = new PagerAdapter(mAppCompatActivity.getSupportFragmentManager());

        for (int contador = 0; contador < mFragmentArrayList.size(); contador++) {

            adapter.addFrag(mFragmentArrayList.get(contador), mFragmentArrayListTitle.get(contador));
        }

        viewPager.setAdapter(adapter);
    }

    class PagerAdapter extends FragmentStatePagerAdapter implements TabLayout.OnTabSelectedListener {

        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @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);
        }

        @Override
        public void onTabSelected(TabLayout.Tab tab) {

            LinearLayout linearLayoutAnimation = (LinearLayout) tab.getCustomView().findViewById(R.id.custom_tab_linear_layout_animation);

            linearLayoutAnimation.setVisibility(View.VISIBLE);

            linearLayoutAnimation.setBackground(ContextCompat.getDrawable(mAppCompatActivity, R.drawable.aba_grande));

            Animation bottomUp = AnimationUtils.loadAnimation(mAppCompatActivity,
                    R.anim.bottom_up);

            linearLayoutAnimation.startAnimation(bottomUp);

            //TODO CHAMA ACTIVITY
        }


        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

            final LinearLayout linearLayoutAnimation = (LinearLayout) tab.getCustomView().findViewById(R.id.custom_tab_linear_layout_animation);

            Animation bottomDown = AnimationUtils.loadAnimation(mAppCompatActivity,
                    R.anim.bottom_down);

            bottomDown.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    linearLayoutAnimation.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });

            linearLayoutAnimation.startAnimation(bottomDown);

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {


        }
    }

    private void createTabIcons() {

        for (int contador = 0; contador < mFragmentArrayList.size(); contador++) {

            LinearLayout tabCustom = (LinearLayout) LayoutInflater.from(mAppCompatActivity).inflate(R.layout.custom_tab, null);
            TextView textViewTabCustom = tabCustom.findViewById(R.id.custom_tab_title);
            textViewTabCustom.setText(mFragmentArrayListTitle.get(contador));
            tabLayout.getTabAt(contador).setCustomView(tabCustom);
        }
    }

    /**
     *
     */
    public void selectTabInitialTab() {

        LinearLayout linearLayoutRoot = (LinearLayout) tabLayout.getTabAt(0).getCustomView().findViewById(R.id.custom_tab_linear_layout_animation);

        linearLayoutRoot.setBackground(ContextCompat.getDrawable(mAppCompatActivity, R.drawable.aba_grande));

        Animation bottomUp = AnimationUtils.loadAnimation(mAppCompatActivity,
                R.anim.bottom_up);

        linearLayoutRoot.startAnimation(bottomUp);
    }
}

When in the activityattab, the Conduit fragment is always the first to be created, position 0. I can not put a TAG to search for this fragment.

Upvotes: 0

Views: 6170

Answers (4)

nimi0112
nimi0112

Reputation: 2135

Inside CustomTabLayout add

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
            {
                @Override
                public void onTabSelected(TabLayout.Tab tab)
                {
                    int position = tab.getPosition();


                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
                }
                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });

Upvotes: 4

Karanveer Singh
Karanveer Singh

Reputation: 1031

Use this:

Fragment f = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + viewPager.getCurrentItem());
if (f instanceof FragmentA) {
} else {
}

Upvotes: 0

Santanu Sur
Santanu Sur

Reputation: 11477

In your activity you can check like this :-

   if(viewPager.getCurrentItem() == 0) {

      // your conduit fragment is visible now
   }

Upvotes: 0

Kanwarpreet Singh
Kanwarpreet Singh

Reputation: 2086

You can use the following way to get current visible fragment. It will return you the position.

viewPager.getCurrentItem();

Upvotes: 0

Related Questions