-3

I've been searching through Stack Overflow but couldn't seem to find something useful about this issue I am having .. Below I have attached the code for the Home Activity that I have, and the XML file for it. I cant seem to get my head around what the problem is, I dunno what I am doing wrong. I want to show the content of a third class (e.g. the a different Fragment class for each of my fragments, basically I want to be able to show all the of the fragments in the same fragment holder in the home activity.. in this case I am trying to open the fragment Bookmarks (men.bookmarks)..

Any suggestions guys?

I didn't include the code for the fragment as it would be a lot of classes then, but If you need it, tell me :) ..

XML file for my HomeActivity:
<?xml version="1.0" encoding="utf-8"?> <android.support.v4.widget.DrawerLayout 
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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start" >


<include
    layout="@layout/app_bar_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_home"
    app:menu="@menu/activity_home_drawer" />

<fragment
    android:name="com.nooriandroid.n007.mybookmarks_v1.Fragment_Bookmarks"
    android:id="@+id/fragBookmarks"
    android:layout_weight="2"
    android:layout_width="25dp"
    android:layout_height="match_parent" />

</android.support.v4.widget.DrawerLayout>

    package com.nooriandroid.n007.mybookmarks_v1;
    import android.app.Fragment;
    import android.app.FragmentManager;
    import android.app.FragmentTransaction;
    import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Activity_Home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    //--------------Variables---------------------//
    private String date_pattern = "hh:mm dd-MM-yyyy";
    private Fragment fragment_bookmarks;
    private Fragment_Favorite fragment_favorite;
    private Fragment_Category fragment_category;
    private Fragment_SharedWith_me fragment_sharedWith_me;
    private Fragment_Myshared fragment_myshared;
    private Activity_Home homeActivity;
    private Fragment_Item_Container fragment_item_container;

    private User user;
    private boolean frag_favorite_visible = false, frag_bookmark_visible = false, frag_category_visible = false,
            frag_myshared_visible = false, frag_sharedwithme__visible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //---------------Customized------------------//
        setTitle("Home");
        ActionBar ab = getSupportActionBar();
        ab.setLogo(R.mipmap.ic_logolight);
        ab.setDisplayUseLogoEnabled(true);
        ab.setDisplayShowHomeEnabled(true);

        fragment_favorite = new Fragment_Favorite();
        fragment_bookmarks = new Fragment_Bookmarks();
        fragment_category = new Fragment_Category();
        fragment_myshared = new Fragment_Myshared();
        fragment_sharedWith_me = new Fragment_SharedWith_me();
        fragment_item_container = new Fragment_Item_Container();
        homeActivity = this;

        FragmentManager fragmentManager = getFragmentManager();
        final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragment_container, fragment_favorite);
        fragmentTransaction.add(R.id.fragment_container, fragment_bookmarks);
        fragmentTransaction.add(R.id.fragment_container, fragment_category);
        fragmentTransaction.add(R.id.fragment_container, fragment_myshared);
        fragmentTransaction.add(R.id.fragment_container, fragment_sharedWith_me);
        frag_favorite_visible = true;
        fragmentTransaction.hide(fragment_bookmarks);
        fragmentTransaction.hide(fragment_category);
        fragmentTransaction.hide(fragment_myshared);
        fragmentTransaction.hide(fragment_sharedWith_me);
        fragmentTransaction.commit();

        goHomeOnclicked();

        user = new User();
        user = (User) getIntent().getSerializableExtra("currentuser");
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.home, menu);
        rundUserSettings();
        SimpleDateFormat format = new SimpleDateFormat(date_pattern);
        String current_date = format.format(new Date());

        TextView nav_textview_Date = (TextView) findViewById(R.id.textView_Date);
        nav_textview_Date.setText(current_date);
        TextView nameLast_textView = (TextView) findViewById(R.id.textView_UsernameLastname);
        nameLast_textView.setText("" + user.getName() + " " + user.getLast_name());

        return true;

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.men_newItem) {
            Intent intent_NewItem = new Intent("com.nooriandroid.n007.mybookmarks_v1.Activity_NewItem");
            startActivity(intent_NewItem);

        } else if (id == R.id.men_bookmarks) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            checkFragmentsStatus(fragmentTransaction);
            fragmentTransaction.show(fragment_bookmarks);
            frag_bookmark_visible = true;
            this.setTitle("Bookmarks"); ///Ombytnings Zirt
            fragmentTransaction.commit(); ///


        } else if (id == R.id.men_category) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            checkFragmentsStatus(fragmentTransaction);
            frag_category_visible= true;
            fragmentTransaction.show(fragment_category);
            fragmentTransaction.commit();
            this.setTitle("Categories ");

            Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
        }
         else if (id == R.id.men_share) {
            Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();

        } else if (id == R.id.men_sharedwithme) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            checkFragmentsStatus(fragmentTransaction);
            frag_sharedwithme__visible = true;
            fragmentTransaction.show(fragment_sharedWith_me);
            fragmentTransaction.commit();
            this.setTitle("Shared with me");
            Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
        } else if (id == R.id.men_myshared) {
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            checkFragmentsStatus(fragmentTransaction);
            frag_myshared_visible = true;
            fragmentTransaction.show(fragment_myshared);
            fragmentTransaction.commit();
            this.setTitle("My shared");
            Toast.makeText(Activity_Home.this,"Not implemented yet.!",Toast.LENGTH_SHORT).show();
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void checkFragmentsStatus(FragmentTransaction fragmentTransaction){
        if (frag_favorite_visible){
            frag_favorite_visible = false;
            fragmentTransaction.hide(fragment_favorite);
        }else if (frag_bookmark_visible){
            frag_bookmark_visible = false;
            fragmentTransaction.hide(fragment_bookmarks);
        }else if (frag_category_visible){
            frag_category_visible = false;
            fragmentTransaction.hide(fragment_category);
        }else if (frag_myshared_visible){
            frag_myshared_visible = false;
            fragmentTransaction.hide(fragment_myshared);
        }else if (frag_sharedwithme__visible){
            frag_sharedwithme__visible = false;
            fragmentTransaction.hide(fragment_sharedWith_me);
        }
    }

    private void goHomeOnclicked(){
        findViewById(R.id.toolbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!frag_favorite_visible){
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    checkFragmentsStatus(fragmentTransaction);
                    frag_favorite_visible = true;
                    fragmentTransaction.show(fragment_favorite);
                    fragmentTransaction.commit();
                    homeActivity.setTitle("Home");
                }
            }
        });
    }

    private boolean rundUserSettings(){
        if (this.user!=null){
            try {
                File file = new File(user.getProfile_pic());
                Uri uri = Uri.fromFile(file);
                ImageView view = (ImageView) findViewById(R.id.imageView_ProfilePic);
                view.setImageURI(uri);

            }catch (Exception e){
                Toast.makeText(Activity_Home.this,"Unable to load profile picture.!",Toast.LENGTH_SHORT).show();
            }
            return true;
        } else {
            return false;
        }
    }
    }
abmy
  • 39
  • 1
  • 8

2 Answers2

1

The code you're using for adding different fragments on the same activity is really messed up. You can use better approach. I'm adding the sample code below:

In the layout of Activity, add this line of code

<FrameLayout
        android:id="@+id/fragBookmarks"
        android:layout_weight="2"
        android:layout_width="25dp"
        android:layout_height="match_parent" />

instead of:

<fragment
android:name="com.nooriandroid.n007.mybookmarks_v1.Fragment_Bookmarks"
android:id="@+id/fragBookmarks"
android:layout_weight="2"
android:layout_width="25dp"
android:layout_height="match_parent" />

Now write this method in your HomeActivity to add different fragments

public void addFragment(Fragment frag, String tag) {
    FragmentTransaction transaction = getFragmentManager().beginTransaction();
    transaction.replace(R.id.fragBookmarks, frag, tag);
    transaction.addToBackStack(getFragmentManager().getBackStackEntryCount() == 0 ? "FirstFragment" : null).commit();
    }
}

This method will help you to add any fragment to this activity on the go. You don't need to add all the fragments from the beginning. Like If now I'm on HomeFragment and I want to open BookmarkFragment on button click from Home, I will write something like;

btnBookmark.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((HomeActivity) getActivity()).addFragment(new BookmarkFragment(), BookmarkFragment.class.getSimpleName()); // This will add the new fragment Bookmark fragment to the activity while adding it to backstack
        }
    });

Now, If you want to go back from BookmarkFragment to HomeFragment, add this method in your HomeActivity

public void popFragment() {
    if (getFragmentManager() == null)
        return;
    getFragmentManager().popBackStack();
}

And Call this function in BookmarkFragment like,

btnBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ((HomeActivity) getActivity()).popFragment(); // This will remove the last added fragment Bookmark fragment
        }
    });
Yasir Tahir
  • 790
  • 1
  • 11
  • 31
  • Thanks a lot four you quick reply. Will give it a try right away and report back soon :) – abmy Apr 21 '16 at 09:21
  • Still missing around with due to other problems, but will get back.. Apparently I cant even do that since my reputation is so low ? – abmy Apr 21 '16 at 12:18
0

DrawerLayout should have only two direct children.If you want to replace different fragments in same activity,create a FrameLayout in the app_bar_home layout.Then in your Activity,do this to replace fragments.

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.frame_layout_id,new yourFragment()).commit();
Ravi Theja
  • 3,371
  • 1
  • 22
  • 34
  • Okay, I might have a lot of unnecessary lines of code, but will try look at your example and report back :) – abmy Apr 21 '16 at 09:22