0

I added a navigation drawer in my app and creates a list of fragments Home,Mobiles,laptops in it. When I ran the app the main activity content launched on start. What I need now is when I click on the items in the navigation drawer it opens the fragment layout but the main content is also displayed, how can I hide the main content when a fragment item is clicked.

This is the code

MainActivity.java:

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener{
 Application myApp;
RSSFeed feed;
ListView lv;
CustomListAdapter adapter;
private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
};

private ShareActionProvider shareActionProvider;
private String[] titles;
private ListView drawerList;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private int currentPosition = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    myApp = getApplication();

    // Get feed form the file
    feed = (RSSFeed) getIntent().getExtras().get("feed");

    // Initialize the variables:
    lv = (ListView) findViewById(R.id.listView);
    lv.setVerticalFadingEdgeEnabled(true);

    // Set an Adapter to the ListView
    adapter = new CustomListAdapter(this);
    lv.setAdapter(adapter);
    titles = getResources().getStringArray(R.array.titles);
    drawerList = (ListView)findViewById(R.id.drawer);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    //Populate the ListView
    drawerList.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_activated_1, titles));
    drawerList.setOnItemClickListener(new DrawerItemClickListener());
    //Display the correct fragment.
    if (savedInstanceState != null) {
        currentPosition = savedInstanceState.getInt("position");
        setActionBarTitle(currentPosition);
    } else {
        selectItem(0);
    }

    // Set on item click listener to the ListView
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            // actions to be performed when a list item clicked
            int pos = arg2;

            Bundle bundle = new Bundle();
            bundle.putSerializable("feed", feed);
            Intent intent = new Intent(MainActivity.this,
                    DetailActivity.class);
            intent.putExtras(bundle);
            intent.putExtra("pos", pos);
            startActivity(intent);

        }
    });

    //Create the ActionBarDrawerToggle
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
            R.string.open_drawer, R.string.close_drawer) {
        //Called when a drawer has settled in a completely closed state
        @Override
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            invalidateOptionsMenu();
        }
        //Called when a drawer has settled in a completely open state.
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            invalidateOptionsMenu();
        }
    };
    drawerLayout.setDrawerListener(drawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    getSupportFragmentManager().addOnBackStackChangedListener(
            new FragmentManager.OnBackStackChangedListener() {
                public void onBackStackChanged() {
                    FragmentManager fragMan = getSupportFragmentManager();
                    Fragment fragment = fragMan.findFragmentByTag("visible_fragment");
                    if (fragment instanceof TopFragment) {
                        currentPosition = 0;
                    }
                    if (fragment instanceof MobileFragment) {
                         currentPosition = 1;
                    }
                    if (fragment instanceof LaptopFragment) {
                        currentPosition = 2;
                    }
                    if (fragment instanceof StoresFragment) {
                        currentPosition = 3;
                    }
                    setActionBarTitle(currentPosition);
                    drawerList.setItemChecked(currentPosition, true);
                }
            }
    );
}

private void selectItem(int position) {
    // update the main content by replacing fragments
    currentPosition = position;
    Fragment fragment;
    switch(position) {
        case 1:
            fragment = new MobileFragment();
            break;
        case 2:
            fragment = new LaptopFragment();
            break;
        case 3:
            fragment = new StoresFragment();
            break;
        default:
            fragment = new TopFragment();
    }
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, fragment, "visible_fragment");
    ft.addToBackStack(null);
   // ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.commit();
    //Set the action bar title
    setActionBarTitle(position);
    //Close drawer
    drawerLayout.closeDrawer(drawerList);
}
@Override
protected void onDestroy() {
    super.onDestroy();
    adapter.imageLoader.clearCache();
    adapter.notifyDataSetChanged();
}

class CustomListAdapter extends BaseAdapter {

    private LayoutInflater layoutInflater;
    public ImageLoader imageLoader;

    public CustomListAdapter(MainActivity activity) {

        layoutInflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader = new ImageLoader(activity.getApplicationContext());
    }

    @Override
    public int getCount() {

        // Set the total list item count
        return feed.getItemCount();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        // Inflate the item layout and set the views
        View listItem = convertView;
        int pos = position;
        if (listItem == null) {
            listItem = layoutInflater.inflate(R.layout.list_item, null);
        }

        // Initialize the views in the layout
        ImageView iv = (ImageView) listItem.findViewById(R.id.thumb);
        TextView tvTitle = (TextView) listItem.findViewById(R.id.title);
        TextView tvDate = (TextView) listItem.findViewById(R.id.date);

        // Set the views in the layout
        imageLoader.DisplayImage(feed.getItem(pos).getImage(), iv);
        tvTitle.setText(feed.getItem(pos).getTitle());
        tvDate.setText(feed.getItem(pos).getDate());

        return listItem;
    }

}



@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    // If the drawer is open, hide action items related to the content view
    boolean drawerOpen = drawerLayout.isDrawerOpen(drawerList);
    menu.findItem(R.id.action_share).setVisible(!drawerOpen);
    return super.onPrepareOptionsMenu(menu);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    // Sync the toggle state after onRestoreInstanceState has occurred.
    drawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    drawerToggle.onConfigurationChanged(newConfig);
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("position", currentPosition);
}

private void setActionBarTitle(int position) {
    String title;
    if (position == 0) {
        title = getResources().getString(R.string.app_name);
    } else {
        title = titles[position];
    }
    getSupportActionBar().setTitle(title);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    MenuItem menuItem = menu.findItem(R.id.action_share);
    shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
    setIntent("This is example text");
    return super.onCreateOptionsMenu(menu);
}

private void setIntent(String text) {
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT, text);
    shareActionProvider.setShareIntent(intent);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (drawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    switch (item.getItemId()) {
        case R.id.action_create_order:
            //Code to run when the Create Order item is clicked
            Intent intent = new Intent(this, OrderActivity.class);
            startActivity(intent);
            return true;
        case R.id.action_settings:
            //Code to run when the settings item is clicked
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

}

activity_main:

<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context="com.example.ayush.gadgetguru.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout
    android:id="@+id/container_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

</LinearLayout>

<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</FrameLayout>

</LinearLayout>

<ListView android:id="@+id/drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#ffffff"/>
</android.support.v4.widget.DrawerLayout>

TopFragment.java:

import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TopFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_top, container, false);
}
}    

fragment_top.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- TODO: Update blank fragment layout -->
 <ListView
    android:id="@+id/listView"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_weight="1" >
</ListView>




</FrameLayout>
  • If your main activity content is displaying immediately upon startup, then it seems that you have it defined in the layout XML, in which case a `FragmentTransaction` is not going to replace it. Put the main content in its own `Fragment`, and load that at the start. Then the `FragmentTransaction`s will work as you're expecting. – Mike M. Jan 21 '16 at 10:41
  • thanks i will give it a try. – Ayush Bagga Jan 21 '16 at 10:45
  • sorry i am not getting where should i put the main content can u help me with this? – Ayush Bagga Jan 21 '16 at 11:01
  • Assuming the main content is in the XML in the ViewGroup with ID `container_body`, you would move all of those Views to another layout file, leaving `container_body` empty. Then use that layout in a Fragment, just like the other Fragments you have in your project, but load it immediately in `onCreate()`. Actually, from your description, it sounds like you want that main content layout in the `HomeFragment`, which you seem to have already created. – Mike M. Jan 21 '16 at 11:12
  • i have posted my activity_main content ,should i move textview View to another layout file as you are suggesting? – Ayush Bagga Jan 21 '16 at 11:45
  • Well, it's not going to get replaced by the `FragmentTransaction`, so however you want to handle that. If the main content is only ever going to be that `TextView`, then you could just change it's visibility as needed, instead of having a whole separate `Fragment` for it. Your design description is a little unclear, though, so I don't know if you mean for that `TextView` to show when you click the Home item, or if you want `HomeFragment` to show. If it's the latter, then yes, put that `TextView` in a separate layout, and inflate that in `HomeFragment`'s `onCreateView()` method. – Mike M. Jan 21 '16 at 11:52
  • no i have more than TextView to display in main content i am currently just trying to deal with this dummy TextView and if it worked i replace it with my actual main content – Ayush Bagga Jan 21 '16 at 11:59
  • hey Mike i have done what you said yesterday and edited the code according to that ,can you please look at the code one more time if that is correct or not because my app is crashing when i am trying to run the app. – Ayush Bagga Jan 22 '16 at 11:18
  • Consult the following posts to determine what exactly is causing the crash: http://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this and http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – Mike M. Jan 22 '16 at 11:23
  • yes i looked into the logcat and there is NullPointerException for listView in line lv.setVerticalFadingEdgeEnabled(true), i think the listView which is defined in the fragment_top has some issue,do you have some idea? – Ayush Bagga Jan 22 '16 at 11:38
  • You're getting an NPE because the Fragment's View hierarchy hasn't been added to the Activity's yet at the point where you're trying to find the ListView. Since the ListView is in the Fragment, you should move all the ListView-related stuff to the Fragment. – Mike M. Jan 22 '16 at 11:44
  • should i move all the related code from MainActivity to TopFragment activity? – Ayush Bagga Jan 22 '16 at 11:49
  • I'm not sure exactly what you're asking, but you should at least move anything directly involved with the `ListView lv` to the Fragment that holds it. – Mike M. Jan 22 '16 at 11:53
  • That ListView contains the data which i parsed from the internet and on clicking that ListView item will open other activity which will not be allowed as it is a Fragment activity So is there anything i can do? – Ayush Bagga Jan 22 '16 at 12:09
  • I don't know what you're asking. You can start an Activity from a Fragment, just like you would from an Activity. – Mike M. Jan 22 '16 at 12:14
  • ok i will give it a try and again thanks for helping me. – Ayush Bagga Jan 22 '16 at 12:37

0 Answers0