Test123
Test123

Reputation: 368

How to change custom-action-bar for several fragment in android?

I am building an android application that is using tablayout.

The tablayout that are been control by the an MainActivity as there swip action, there name etc.

Now I want to control there custom-action-bar from MainActivity.

suppose if oneFragment is open custome_action_bar_one should been applied. When user goes to SecondFragment, it's call custome_action_bar_second.

Here is the code of TabLayout that I am using:

package info.androidhive.tabsswipe.adapter;

public class TabsPagerAdapter extends FragmentPagerAdapter {

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

@Override
public Fragment getItem(int index) {

    switch (index) {
    case 0:
        // Top Rated fragment activity
        return new TopRatedFragment();
    case 1:
        // Games fragment activity
        return new GamesFragment();
    case 2:
        // Movies fragment activity
        return new MoviesFragment();
    }

    return null;
}

@Override
public int getCount() {
    // get item count - equal to number of tabs
    return 3;
}
}

Here is the code used for making an custome_action_bar:

getActivity().getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#0077d1")));
    ActionBar mActionBar = getActivity().getActionBar();
    getActivity().getActionBar().setIcon(
            new ColorDrawable(getResources().getColor(
                    android.R.color.transparent)));
    mActionBar.setDisplayShowHomeEnabled(true);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(getActivity());
    View mCustomView = mInflater.inflate(R.layout.custom_actionbar2, null);
    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);

Here is my fragment code:

getActivity().getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#0077d1")));
    ActionBar mActionBar = getActivity().getActionBar();
    getActivity().getActionBar().setIcon(
            new ColorDrawable(getResources().getColor(
                    android.R.color.transparent)));
    mActionBar.setDisplayShowHomeEnabled(true);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(getActivity());
    View mCustomView = mInflater.inflate(R.layout.custom_actionbar2, null);
    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);
    ImageButton btnhst = (ImageButton) getActivity.findViewById(
            R.id.hstbtn);

Upvotes: 0

Views: 1580

Answers (1)

madhavan
madhavan

Reputation: 50

@sonam you have used

ImageButton btnhst = (ImageButton) **getActivity**.findViewById(R.id.hstbtn);

instead getActivity() try using :

mCustomView.findViewById()

All the best

Upvotes: 1

Related Questions