0

I have 11 Fragments that are hosted in MainActivity.class, these Fragment use RecyclerView to display items. The items are clickable, When they are clicked items parse data in DetailActivity.class. The MainActivity is the parent activity. I want to implement onBackPressed(); such that when the user clicks the homeBack button in the detail activity they will be returned to previous Fragment(previous position in the MianActivity)

MainActivity.class

public class MainActivity extends AppCompatActivity implements MaterialTabListener, View.OnClickListener, FragmentManager.OnBackStackChangedListener {

    private static final int JOB_ID = 100;
    private Toolbar toolbar;
    private ViewPager mPager;
    private MaterialTabHost mTabHost;
    private SlidingTabLayout mTabs;
    private ViewPagerAdapter adapter;

    public static final int MOVIES_SEARCH_RESULTS = 1;
    public static final int MOVIEE_HITS = 0;
    public static final int MOVIES_UPCOMING = 2;
    public static final int NEWS_OPINION = 3;
    public static final int NEWS_CULTURE = 4;
    public static final int NEWS_BUSINESS = 5;
    public static final int NEWS_LIFESTYLE = 6;
    public static final int NEWS_FASHION = 7;
    public static final int NEWS_ENVIRONMENT = 8;
    public static final int NEWS_TECH = 9;
    public static final int NEWS_TRAVEL = 10;


    public static final int TAB_COUNT = 11;
    private JobScheduler mJobScheduler;
    Realm mRealm;
    FragmentManager mFragmentManager;
    private static final String TAG_SORT_NAME = "sortName";
    private static final String TAG_SORT_DATE = "sortDate";
    private static final String TAG_SORT_RATINGS = "sortRatings";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mJobScheduler = JobScheduler.getInstance(this);
        mRealm = Realm.getDefaultInstance();
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
        mPager = (ViewPager) findViewById(R.id.pager);
        mPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
        mTabs = (SlidingTabLayout) findViewById(R.id.tabs);
        /*mTabHost = (MaterialTabHost) findViewById(R.id.materialTabHost);*/
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(adapter);
        mTabs.setViewPager(mPager);
        mFragmentManager=getSupportFragmentManager();
        mFragmentManager.addOnBackStackChangedListener(this);
        Fragment fragment = new Business();
        // if you don't run on prior to Android 3.0 use getFragmentManager();
        mFragmentManager.beginTransaction().replace(R.id.businessFragment, fragment).addToBackStack(null).commit();
        // R.id.frame_container is the id of FrameLayout in activity_main.xml





    }

    @Override
    public void onBackPressed() {
        if(mFragmentManager.getBackStackEntryCount() == 0){
            finish();
        }else{
            super.onBackPressed();
        }
    }

    public void constructJob() {
        JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(this, MyService.class));
    }

    private void buildFAB() {
        // in Activity Context
        ImageView icon = new ImageView(this); // Create an icon
        icon.setImageResource(R.drawable.ic_action_new);
        FloatingActionButton actionButton = new FloatingActionButton.Builder(this)
                .setContentView(icon)
                .setBackgroundDrawable(R.drawable.selector_button_red)
                .build();

// repeat many times:
        ImageView iconSortName = new ImageView(this);
        iconSortName.setImageResource(R.drawable.ic_action_alphabets);
        ImageView iconSortDate = new ImageView(this);
        iconSortDate.setImageResource(R.drawable.ic_action_calendar);
        ImageView iconSortRatings = new ImageView(this);
        iconSortRatings.setImageResource(R.drawable.ic_action_important);

        // set background for all the buttons
        SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
        itemBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.selector_sub_button_gray));

        // build the sub buttons
        SubActionButton buttonSortName = itemBuilder.setContentView(iconSortName).build();
        SubActionButton buttonSortDate = itemBuilder.setContentView(iconSortDate).build();
        SubActionButton buttonSortRatings = itemBuilder.setContentView(iconSortRatings).build();

        buttonSortName.setTag(TAG_SORT_NAME);
        buttonSortDate.setTag(TAG_SORT_DATE);
        buttonSortRatings.setTag(TAG_SORT_RATINGS);

        buttonSortName.setOnClickListener(this);
        buttonSortDate.setOnClickListener(this);
        buttonSortRatings.setOnClickListener(this);
        //Add the sub buttons to the main floating action button
        FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this)
                .addSubActionView(buttonSortName)
                .addSubActionView(buttonSortDate)
                .addSubActionView(buttonSortRatings)

                        // ...
                .attachTo(actionButton)
                .build();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case R.id.action_settings:
                Toast.makeText(this, "Hey you just hit " + item.getTitle(), Toast.LENGTH_SHORT).show();
                return true;
            case android.R.id.home:
                getSupportFragmentManager().popBackStack();
                return true;

        }



        return onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(MaterialTab tab) {
        mPager.setCurrentItem(tab.getPosition());

    }

    @Override
    public void onTabReselected(MaterialTab tab) {

    }

    @Override
    public void onTabUnselected(MaterialTab tab) {

    }

    @Override
    public void onClick(View v) {
        //call instantiate item since getItem may return null depending on whether the PagerAdapter is of type FragmentPagerAdapter or FragmentStatePagerAdapter
        Fragment fragment = (Fragment) adapter.instantiateItem(mPager, mPager.getCurrentItem());
        if (fragment instanceof SortListener) {

            if (v.getTag().equals(TAG_SORT_NAME)) {
                //call the sort by name method on any Fragment that implements sortlistener
                ((SortListener) fragment).onSortByName();
            }
            if (v.getTag().equals(TAG_SORT_DATE)) {
                //call the sort by date method on any Fragment that implements sortlistener
                ((SortListener) fragment).onSortByDate();
            }
            if (v.getTag().equals(TAG_SORT_RATINGS)) {
                //call the sort by ratings method on any Fragment that implements sortlistener
                ((SortListener) fragment).onSortByRatings();
            }
        }
    }

    @Override
    public void onBackStackChanged() {
     /*   if (getSupportFragmentManager().getBackStackEntryCount()==1){
            finish();
        }else {
            super.onBackPressed();
        }*/

    }


   /* private void replaceFragment(Fragment fragment) {
        String backStackName = fragment.getClass().getName();
        boolean fragmentPopped = mFragmentManager.popBackStackImmediate(backStackName, 0);
        if (!fragmentPopped) {
            fragmentTransaction.replace(R.id.container, fragment);
            fragmentTransaction.addToBackStack(backStackName);
            fragmentTransaction.commit();
        }
    }*/

    class ViewPagerAdapter extends FragmentStatePagerAdapter {
        /*private String tabs[] = new String[]{"Tab 1 ", "Tab 2 ", " Tab 3"};*/
     /*   int icons[] = {R.drawable.ic_home_black_24dp,
                R.drawable.ic_library_books_black_24dp,
                R.drawable.ic_person_black_24dp,

        };*/

        String[] tabText;
        FragmentManager fragmentManager;

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
            tabText = getResources().getStringArray(R.array.tabs);
            fragmentManager = fm;

        }

        @Override
        public Fragment getItem(int num) {
            Fragment fragment = null;
            switch (num) {
                case MOVIES_SEARCH_RESULTS:
                    fragment = FragmentSearch.newInstance("", "");
                    break;
                case MOVIEE_HITS:
                    fragment = FragmentBoxOffice.newInstance("", "");

                    break;
                case MOVIES_UPCOMING:
                    fragment = FragmentUpcoming.newInstance("", "");

                    break;
                case NEWS_OPINION:
                    fragment = Opinion.newInstance("", "");
                    break;
                case NEWS_CULTURE:
                    fragment = Culture.newInstance("", "");
                    break;
                case NEWS_BUSINESS:
                    fragment = Business.newInstance("", "");
                    break;
                case NEWS_LIFESTYLE:
                    fragment = Lifestyle.newInstance("", "");
                    break;
                case NEWS_FASHION:
                    fragment = Fashion.newInstance("", "");
                    break;
                case NEWS_ENVIRONMENT:
                    fragment = Environment.newInstance("", "");
                    break;
                case NEWS_TECH:
                    fragment = Tech.newInstance("", "");
                    break;
                case NEWS_TRAVEL:
                    fragment = Travel.newInstance("", "");
                    break;
            }
            return fragment;
        }


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

        @Override

        public CharSequence getPageTitle(int position) {
            return tabText[position];
        }

       /* private Drawable getIcon(int position) {
            return getResources().getDrawable(icons[position]);
        }*/
    }

}

DetailActivity.class

    public class DetailActivity extends AppCompatActivity  {
    private Toolbar mToolbar;
    private ViewPager mPager;
    private ViewGroup mCointainerTooobar;
    private VolleySingleton volleySingleton;
    private ImageLoader imageLoader;

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

        mToolbar = (Toolbar) findViewById(R.id.toolbarf);
        setSupportActionBar(mToolbar);
        final CollapsingToolbarLayout collapsingToolbarLayout =
                (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar_layout);
        Bundle extra = getIntent().getExtras();
        String detailsSectionId = extra.getString("SectionId");
        collapsingToolbarLayout.setTitle(detailsSectionId.toString().trim());
        ImageView flexibleHeader = (ImageView) findViewById(R.id.ivProfileImage);
        mCointainerTooobar = (ViewGroup) findViewById(R.id.container_app_bar);
        volleySingleton = VolleySingleton.getsInstance();
        imageLoader = volleySingleton.getImageLoader();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        displayingDetails();
   /*     Bitmap mBitmap= BitmapFactory.decodeResource(getResources(), R.id.ivProfileImage);
        Palette.from(mBitmap).generate(new Palette.PaletteAsyncListener() {

            @Override


            public void onGenerated(Palette palette) {
                String mutecolor;

                collapsingToolbarLayout.setContentScrim(Palette.g);
            }
        });*/


    }

    @Override
    public void onBackPressed() {
        if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }

    public void displayingDetails() {
        // seactionId
        Bundle extra = getIntent().getExtras();
        String detailsSectionId = extra.getString("SectionId");
        TextView sectionText = (TextView) findViewById(R.id.DetailsSectionId);
        sectionText.setText(detailsSectionId);
        // Title
        Bundle titleText = getIntent().getExtras();
        String title = titleText.getString("title");
        TextView titleView = (TextView) findViewById(R.id.DetailNews_title);
        titleView.setText(title);
        // Thumbnail
        Bundle mUrlThumbnail = getIntent().getExtras();
        String urlThumbnail = mUrlThumbnail.getString("UrlThumbnail");
        final ImageView urlThumbnailView = (ImageView) findViewById(R.id.ivProfileImage);
        if (urlThumbnail != null) {
            imageLoader.get(urlThumbnail, new ImageLoader.ImageListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }

                @Override
                public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                    urlThumbnailView.setImageBitmap(response.getBitmap());
                }
            });
            urlThumbnailView.setBackgroundDrawable(Drawable.createFromPath(urlThumbnail));
        }
        // Body
        Bundle mBody = getIntent().getExtras();
        /*String body= Html.fromHtml(mBody.getString("body"));*/
        String body = mBody.getString("body");
        TextView bodyView = (TextView) findViewById(R.id.DetailsNews_description);
        bodyView.setText(Html.fromHtml(body));
        bodyView.setMaxLines(1000000);


    }

   /* @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                L.t(DetailActivity.this, "this is the details activity");
                getFragmentManager().popBackStack();

                return true;
        }
        return super.onOptionsItemSelected(item);
    }*/
}

How do I implement this functionality, Any solution will be highly appreciated ..

1 Answers1

0

When you return from your detail activity you want to resume the MainActivity at the position you were at the last time. You can preserve a marker of your current fragment and in your OnResume function you can replace the fragment with the fragment it was on previously.

If you want to implement the Back button press from inside your fragment. Here's a suitable code to do this. This is much relevant with the question you asked. But I put it here for the headline of the question.

Inside your onCreateView set a KeyListener like this.

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

    // Handle back press action when action mode is on.
    v.setFocusableInTouchMode(true);
    v.requestFocus();
    v.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK) {

                if (haveToDoSomething) {
                    // Do something
                }
                else return false;
            }

            return true;
        }
    });
}
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98