简体   繁体   中英

Android get tabLayout from a fragment

I was wondering if there's a way to access the tabLayout from a fragment.

I declare my TabLayout below and I disable all the tabs.

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

LinearLayout tabStrip = ((LinearLayout)tabLayout.getChildAt(0));
    for(int i = 0; i < tabStrip.getChildCount(); i++) {
       tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
           @Override
           public boolean onTouch(View v, MotionEvent event) {
                return true;
           }
       });
    }

What I would like to do is be able to enable them in a fragment inside a ClickListener.

I am not sure I should declare the tabLayout static and access it like that or if there's a correct way of doing this.

I apologize if I did not explain it correct - still a little new to Android.

Declaring tablayout as static variable is a bad way of handling the scenario. You can make use of interface to achieve this instead. Please check out the official link on how to communicate between fragment and activity, it is pretty simple. https://developer.android.com/training/basics/fragments/communicating.html

Using interface to communicate between fragment and activity, for sample

create interface.

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onClickToEnableTab();
}

implement it in activity. Do the code to enable your tab

public class Activity implement OnFragmentInteractionListener{
    @Override
    public void onClickToEnableTab() {
       // TODO : Enable you tab layout
    }
}

in fragment

public class YourFragment extends Fragment {
private OnFragmentInteractionListener mListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }  
}

And then, in your fragment inside onClickListenner you can call

mListener.onClickToEnableTab();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM