Android Navigation Drawer Content Frame Cannot be resolved - android

I am using the following code to implement a simple navigation drawer based on the sample given in the Android Developers site.
public class MainActivity extends ActionBarActivity {
Toolbar toolbar;
DrawerLayout mDrawerLayout;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
ListView mDrawerList;
private String[] mDrawerItems;
ActionBarDrawerToggle drawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
mDrawerItems = getResources().getStringArray(R.array.graph_array);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
setSupportActionBar(toolbar);
mTitle = mDrawerTitle = getTitle();
toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
mDrawerLayout = (DrawerLayout) findViewById(R.id.navDrawer);
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.primaryDark));
drawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.abc_action_bar_home_description, R.string.abc_action_bar_home_description) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(drawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mDrawerItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
//Fragment fragment = new PlanetFragment();
//Bundle args = new Bundle();
//args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
//fragment.setArguments(args);
if (position == 0) {
Fragment frag1 = new Fragment1();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, frag1).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mDrawerItems[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else if (position == 1) {
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#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);
// Pass any configuration change to the drawer toggls
drawerToggle.onConfigurationChanged(newConfig);
}
#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);
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);
}
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.graph_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
But I get an error saying "content_frame cannot be resolved". How do I fix this ?
EDIT :
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/navDrawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
<com.example.shivam.signalprocessing1.ScrimInsetsFrameLayout xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/scrimInsetsFrameLayout"
android:layout_width="320dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/white"
android:elevation="10dp"
android:fitsSystemWindows="true"
app:insetForeground="#4000">
<RelativeLayout
android:id="#+id/left_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/white"
android:fitsSystemWindows="true"
android:orientation="vertical">
<ImageView
android:id="#+id/image_view"
android:layout_width="match_parent"
android:layout_height="144dp"
android:scaleType="centerCrop"
android:background="#drawable/material_wallpaper" />
<ListView
android:id="#+id/list_view_drawer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/image_view"
android:choiceMode="singleChoice" />
</RelativeLayout>
</com.example.shivam.signalprocessing1.ScrimInsetsFrameLayout>
</android.support.v4.widget.DrawerLayout>
Thanks !

Change the id of the frame... its normally container... But change it to content_frame and you are good.

Related

Scrollview inside DrawerLayout prevents ListView buttons from working [duplicate]

I am trying to use the sliding navigation drawer in the app. However it seems that it's not handling the OnItemClick method. When I click on an item nothing happens.How can I make it work?Thanks
//MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer_layout = (DrawerLayout)findViewById(R.id.drawerLayout);
list_view = (ListView)findViewById(R.id.drawerList);
menu_items = getResources().getStringArray(R.array.nav_drawer_items);
list_view.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, menu_items));
list_view.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, menu_items[position] + " was selected", Toast.LENGTH_LONG).show();
}
// MainActivity.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#android:color/white"
android:divider="#android:color/black"
android:dividerHeight="1dp"
android:listSelector="#android:color/black"
android:choiceMode="singleChoice"
/>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:ignore="MergeRootFrame"
tools:context="com.example.MainActivity"
>
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textview1"
android:layout_gravity="center"
android:textStyle="bold"
android:textSize="20sp"
android:gravity="center"
android:layout_marginTop="30dp"/>
<Button
android:id="#+id/Button1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#drawable/ok_button"
android:layout_marginTop="20dp"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Your DrawerLayout's child Views are incorrectly z-ordered. The View for the drawer - in this case, the ListView - needs to be listed last in order to be on top of everything else.
Do it Simple like this: Add these line of code after setContentView(R.layout.activity_main); or what ever your activity name is.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Initializing Drawer Layout and ActionBarToggle
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){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
Then Move to next step:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId){
try {
switch (itemId) {
case R.id.nav_menu1:
startActivity(new Intent(this, BActivity.class));
break;
case R.id.nav_menu2:
startActivity(new Intent(this, CActivity.class));
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
For Left Menu Drawer Complete Simple you can try the following Simple....
MainActivity.class
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] navMenuTitles;
private ArrayList<MainDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for lefdrawer
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(
R.array.dashboard_leftMenu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_dashboard_layout);
mDrawerList = (ListView) findViewById(R.id.main_dash_left_list_drawer);
navDrawerItems = new ArrayList<MainDrawerItem>();
navDrawerItems.add(new MainDrawerItem(navMenuTitles[0], 0,
null, false));
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons//
// invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
Toast.makeText(MainActivity.this, ..... + " was selected",Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
MainDrawerItem.class
public class MainDrawerItem {
private String title;
public MainDrawerItem(){
}
public MainDrawerItem(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
}
For Adapter Class
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<MainDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<MainDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}

Switching fragments in navigation drawer on item click

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>

Navigation Drawer not closing

I have implemented a navigationdrawer in android.I don't understand how to close the drawer when a item from the drawer list is selected.The foolowing code gives me a null pointer exception.
The mainactivity:
public class MainActivity extends ActionBarActivity {
String[] planet={"earth","mars","jupiter"};
ListView lv;
DrawerLayout mDrawerLayout;
NavigationDrawerFragment navigationDrawerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(savedInstanceState==null){
earth earthfrag=new earth();
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction transaction=fragmentManager.beginTransaction();
transaction.add(R.id.mainactivity,earthfrag,"earth").commit();
}
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
mDrawerLayout=(DrawerLayout)findViewById(R.id.nav_drawer);
navigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager().findFragmentById(R.id.drawer_fragment);
navigationDrawerFragment.setup(mDrawerLayout, toolbar);
lv= (ListView) findViewById(R.id.listView);
lv.setAdapter(new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,planet));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction transaction=fragmentManager.beginTransaction();
if(position==2){
jupiter jupiterfrag=new jupiter();
transaction.replace(R.id.mainactivity, jupiterfrag, "jupiter").commit();
}
if (position==1){
mars marsfrag=new mars();
transaction.replace(R.id.mainactivity,marsfrag,"mars").commit();
}
if (position==0){
earth earthfrag=new earth();
transaction.replace(R.id.mainactivity,earthfrag,"earth").commit();
}
mDrawerLayout.closeDrawer(lv);
}
});
}
#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);
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);
}
}
The NavigationDrawerFragment :
public class NavigationDrawerFragment extends Fragment {
private ActionBarDrawerToggle mActionBarDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.drawer_fragment,container,false);
}
public void setup(DrawerLayout drawerLayout,Toolbar toolbar) {
mDrawerLayout=drawerLayout;
mActionBarDrawerToggle=new ActionBarDrawerToggle(getActivity(),mDrawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close){
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mActionBarDrawerToggle.syncState();
}
});
}
}
The activity_main.xml:
<?xml version="1.0"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/nav_drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<include
android:id="#+id/app_bar"
layout="#layout/app_bar" />
<RelativeLayout
android:id="#+id/mainactivity"
android:layout_width="match_parent"
android:layout_height="match_parent"></RelativeLayout>
</LinearLayout>
<fragment
android:id="#+id/drawer_fragment"
android:name="com.example.joy.ecoapp.NavigationDrawerFragment"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
tools:layout="#layout/drawer_fragment" />
</android.support.v4.widget.DrawerLayout>
I believe you need to wrap the fragment in a container, e.g. a LinearLayout. Then use that container as the drawer:
<LinearLayout
android:id="#+id/lv_wrapper"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#android:color/background_light"
android:padding="5dp" >
<fragment
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="#+id/drawer_fragment"
tools:layout="#layout/drawer_fragment"
android:name="com.example.joy.ecoapp.NavigationDrawerFragment" />
</LinearLayout>
Then in your code instead of calling
mDrawerLayout.closeDrawer(lv);
call it with your new wrapper:
mDrawerLayout.closeDrawer(findViewById(R.id.lv_wrapper);

Sliding navigation drawer not handling clicks on menu items android

I am trying to use the sliding navigation drawer in the app. However it seems that it's not handling the OnItemClick method. When I click on an item nothing happens.How can I make it work?Thanks
//MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
drawer_layout = (DrawerLayout)findViewById(R.id.drawerLayout);
list_view = (ListView)findViewById(R.id.drawerList);
menu_items = getResources().getStringArray(R.array.nav_drawer_items);
list_view.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, menu_items));
list_view.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, menu_items[position] + " was selected", Toast.LENGTH_LONG).show();
}
// MainActivity.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawerLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/mainContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView android:id="#+id/drawerList"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="left"
android:background="#android:color/white"
android:divider="#android:color/black"
android:dividerHeight="1dp"
android:listSelector="#android:color/black"
android:choiceMode="singleChoice"
/>
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:ignore="MergeRootFrame"
tools:context="com.example.MainActivity"
>
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/textview1"
android:layout_gravity="center"
android:textStyle="bold"
android:textSize="20sp"
android:gravity="center"
android:layout_marginTop="30dp"/>
<Button
android:id="#+id/Button1"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:background="#drawable/ok_button"
android:layout_marginTop="20dp"/>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Your DrawerLayout's child Views are incorrectly z-ordered. The View for the drawer - in this case, the ListView - needs to be listed last in order to be on top of everything else.
Do it Simple like this: Add these line of code after setContentView(R.layout.activity_main); or what ever your activity name is.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Initializing Drawer Layout and ActionBarToggle
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){
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.bringToFront();
Then Move to next step:
#Override
public boolean onNavigationItemSelected(MenuItem item) {
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId){
try {
switch (itemId) {
case R.id.nav_menu1:
startActivity(new Intent(this, BActivity.class));
break;
case R.id.nav_menu2:
startActivity(new Intent(this, CActivity.class));
break;
}
}
catch (Exception e)
{
e.printStackTrace();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer);
drawer.closeDrawer(GravityCompat.START);
}
For Left Menu Drawer Complete Simple you can try the following Simple....
MainActivity.class
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] navMenuTitles;
private ArrayList<MainDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for lefdrawer
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(
R.array.dashboard_leftMenu);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_dashboard_layout);
mDrawerList = (ListView) findViewById(R.id.main_dash_left_list_drawer);
navDrawerItems = new ArrayList<MainDrawerItem>();
navDrawerItems.add(new MainDrawerItem(navMenuTitles[0], 0,
null, false));
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, // nav menu toggle icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons//
// invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
private void displayView(int position) {
// update the main content by replacing fragments
switch (position) {
case 0:
Toast.makeText(MainActivity.this, ..... + " was selected",Toast.LENGTH_LONG).show();
break;
default:
break;
}
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
MainDrawerItem.class
public class MainDrawerItem {
private String title;
public MainDrawerItem(){
}
public MainDrawerItem(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
}
For Adapter Class
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<MainDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<MainDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawer_list_item, null);
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}

Showing Map in a Fragment

In my application i want to show google map in a Fragment. My activity class is given below.
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_launcher, R.string.app_name,
R.string.action_settings) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_websearch:
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, "Nothing", Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
onItemSelected(mPlanetTitles[position]);
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void onItemSelected(String link) {
DetailFragment fragment = (DetailFragment) getFragmentManager()
.findFragmentById(R.id.detailFragment);
fragment.setText(link);
}
}
As shown in the code in the Activity i am using a DrawyerLayout inside that there are four items. When the user press the Item. I am showing Fragment where the MapFragment kept inside.
Please see the Main Xml layout file.
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/detailFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
class="com.example.mynavigation.DetailFragment"
android:visibility="invisible" >
</fragment>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#111"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>
My Fragment Class.
public class DetailFragment extends Fragment {
GoogleMap map ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
System.out.println("kkkkkkkkkkkk");
View view = inflater.inflate(R.layout.fragment_rssitem_detail,
container, true);
return view;
}
public void setText(String item) {
System.out.println("set Tewxt");
TextView view = (TextView) getView().findViewById(R.id.detailsText);
view.setText(item);
}
}
And the fragment_rssitem_detail.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/detailsText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginTop="20dip"
android:text="Default Text"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30dip" />
<FrameLayout
android:id="#+id/map_frame"
android:layout_width="fill_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
class="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp" />
</FrameLayout>
<!-- <ListView
android:id="#+id/list_fragment"
android:name="com.myapp.ListFragment"
android:layout_width="wrap_content"
android:layout_height="fill_parent" /> -->
</LinearLayout>
Put only LinearLayout at where you want to put map in your xml and push map programatically as below:
private SupportMapFragment mapFragment;
mapFragment = new SupportMapFragment();
addFragment(lnrMap.getId(), mapFragment); //lnrMap is your LinearLayout from xml.
googleMap = mapFragment.getExtendedMap();
AddFragment Method(),Put this method in your DetailFragment class:
public void addFragment(int layoutId, Fragment fragment) {
FragmentManager fm = getChildFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(layoutId, fragment);
ft.commit();
}

Categories

Resources