Navigation Drawer with backword compatibility android - android

I am having a application which is having four different activities. Now i want to add a navigation drawer in application to navigates those activities. Can any one give an example or tutorial for navigation drawer for different activity with back word compatibility.I have seen example for fragments but I need example for activities.

You need to use appcompact from the Support Library.
Your activity needs to extend ActionBarActivity.
In your Activity
public class MainActivity extends ActionBarActivity {
Import
import android.support.v7.app.ActionBarActivity;
Instead of getActionBar() use getSupportActionbar()
Use Them.AppCompact
Or use ActionBarSherlock library.
https://stackoverflow.com/questions/20071004/add-icon-in-drawerlist-by-actionbarsherlock/20077469#20077469
Example:
MainActivity.java
public class MainActivity extends ActionBarActivity {
// Fields -----------------------------------------------------------------
private DrawerLayout drawerLayout;
private ListView drawerList;
private ActionBarDrawerToggle drawerToggle;
private MenuListAdapter menuAdapter;
private int[] icons;
private Fragment fragment1;
private Fragment fragment2;
private Fragment fragment3;
private CharSequence drawerTitle;
private CharSequence title;
private final String[] titles = new String[]{
"Title Fragment #1",
"Title Fragment #2",
"Title Fragment #3"
};
private final String[] subtitles = new String[]{
"Subtitle Fragment #1",
"Subtitle Fragment #2",
"Subtitle Fragment #3"
};
// Lifecycle Callbacks ----------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
// Base implemenation
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Instantiate the fragments
fragment1 = new Fragment1();
fragment2 = new Fragment2();
fragment3 = new Fragment3();
// Get the title from this activity
title = drawerTitle = getTitle();
// Get the icons from the drawables folder
icons = new int[]{
R.drawable.action_about,
R.drawable.action_settings,
R.drawable.collections_cloud
};
// Get the drawer layout from the XML file and the ListView inside it
drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
drawerList = (ListView)findViewById(R.id.listview_drawer);
// Set a custom shadow over that overlays the main content
// when the drawer opens
drawerLayout.setDrawerShadow(
R.drawable.drawer_shadow, GravityCompat.START);
// Pass the string arrays to the MenuListAdapter, set the drawer
// list adapter to it and set up its click listener
menuAdapter = new MenuListAdapter(
MainActivity.this, titles, subtitles, icons);
drawerList.setAdapter(menuAdapter);
drawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable the action bar to have up navigation
getSupportActionBar().setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Allow the the action bar to toggle the drawer
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View view){
super.onDrawerClosed(view);
}
public void onDrawerOpened(View view){
getSupportActionBar().setTitle(drawerTitle);
super.onDrawerOpened(view);
}
};
drawerLayout.setDrawerListener(drawerToggle);
// If this is the first time opening this activity,
// start with loading fragment #1
if (savedInstanceState == null){
selectItem(0);
}
}
// Methods ----------------------------------------------------------------
#Override
public boolean onOptionsItemSelected(MenuItem item){
// If the user has pressed the action bar icon
if (item.getItemId() == android.R.id.home){
// If the drawer is open, close it; vice versa
if (drawerLayout.isDrawerOpen(drawerList)){
drawerLayout.closeDrawer(drawerList);
} else {
drawerLayout.openDrawer(drawerList);
}
}
// Finish by letting the super class do the rest
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
// Call the super implementation and synchronize the drawer
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
// Call the super implemenation on this activity
// and the drawer toggle object
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
private void selectItem(int position){
// Create a new fragment transaction and start it
FragmentTransaction fragTran = getSupportFragmentManager()
.beginTransaction();
// Locate the position selected replace the content view
// with the fragment of the number selected
switch (position){
case 0:{
fragTran.replace(R.id.content_frame, fragment1);
break;
}
case 1:{
fragTran.replace(R.id.content_frame, fragment2);
break;
}
case 2:{
fragTran.replace(R.id.content_frame, fragment3);
break;
}
}
// Commit the transaction and close the drawer
fragTran.commit();
drawerList.setItemChecked(position, true);
drawerLayout.closeDrawer(drawerList);
}
public void setTitle(CharSequence title){
// Save the passed in title and set the action bar title
this.title = title;
getSupportActionBar().setTitle(title);
}
// Classes ----------------------------------------------------------------
private class DrawerItemClickListener
implements ListView.OnItemClickListener{
#Override
public void onItemClick(
AdapterView<?> parent,
View view,
int position,
long id) {
// When clicked, select open the appropriate fragment
selectItem(position);
}
}
}
activity_main.xml
<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"/>
<ListView
android:id="#+id/listview_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>
public class MenuListAdapter extends BaseAdapter {
// Fields -----------------------------------------------------------------
private Context mcontext;
private String[] titles;
private String[] subtitles;
private int[] icons;
private LayoutInflater inflater;
// Constructor ------------------------------------------------------------
public MenuListAdapter(
Context context,
String[] titles,
String[] subtitles,
int[] icons){
mcontext = context;
this.titles = titles;
this.subtitles = subtitles;
this.icons = icons;
inflater = (LayoutInflater)mcontext.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
// Accessors --------------------------------------------------------------
#Override
public int getCount(){
return titles.length;
}
#Override
public Object getItem(int position){
return titles[position];
}
#Override
public long getItemId(int position){
return position;
}
// Methods ----------------------------------------------------------------
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder viewHolder;
// Only inflate the view if convertView is null
if (convertView == null){
viewHolder = new ViewHolder();
if(inflater!=null)
{
convertView = inflater.inflate(
R.layout.drawer_list_item, parent, false);
viewHolder.txtTitle = (TextView)convertView.findViewById(
R.id.title);
viewHolder.txtSubtitle = (TextView)convertView.findViewById(
R.id.subtitle);
viewHolder.imgIcon = (ImageView)convertView.findViewById(
R.id.icon);
// This is the first time this view has been inflated,
// so store the view holder in its tag fields
convertView.setTag(viewHolder);
}
else
{
Log.i("........",""+null);
}
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
// Set the views fields as needed
viewHolder.txtTitle.setText(titles[position]);
viewHolder.txtSubtitle.setText(subtitles[position]);
viewHolder.imgIcon.setImageResource(icons[position]);
return convertView;
}
// Classes ----------------------------------------------------------------
static class ViewHolder {
TextView txtTitle;
TextView txtSubtitle;
ImageView imgIcon;
}
}
drawr_list_item.xml
<?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:background="#android:color/darker_gray"
android:orientation="horizontal"
style="?attr/dropdownListPreferredItemHeight" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center_vertical|left"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
style="?attr/spinnerDropDownItemStyle"/>
<TextView
android:id="#+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
style="?attr/spinnerDropDownItemStyle"/>
</LinearLayout>
</LinearLayout>
fragment1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
fragment2.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Fragment2"/>
</RelativeLayout>
fragment3.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/Fragment3"/>
</RelativeLayout>
Fragment1.java
public class Fragment1 extends Fragment {
String[] titles={"A","B","C"};
#Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment1, container, false);
ListView lv = (ListView) rootView.findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,titles);
lv.setAdapter(adapter);
return rootView;
}
}
Fragment2.java
public class Fragment2 extends Fragment {
#Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment2, container, false);
return rootView;
}
}
Fragment3.java
public class Fragment3 extends Fragment {
#Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment3, container, false);
return rootView;
}
}
Add theme in manifest
android:theme="#style/Theme.AppCompat"
Snap

A new version of the v4 support library (release 13) which contains support for the Navigation Drawer pattern.
Check out the below tutorial Links for Navigation Drawer which provides the compatibility library of Navigation Drawer with the implementation in it.
1) Sherlock Navigation Drawer
2) NavDrawerExampleAppCompat-v7
3) Navigation Drawer in Android
4) Create Navigation Drawer
Hope this will help you.

Navigation Drawer which is implemented in the using DrawerLayout , if not using any externel library, is avaliable in the Android Support Package. So it can be using about API level 4 which Donut(1.6). Use this link for more info DrawerLayout

Related

Android Navigation draw not displaying images and text

I am trying to create a navigation draw which displays text and images. My project builds OK but when I open the navigation draw there is no text or images displayed. I have created a layout file for the image and text to be displayed on the navigation draw and I have set the adapter for the navigation draw as well as creating my own Adapter class.
I cant see what is wrong but something obviously is :) Any help is greatly appreciated.
Here are my files
navigation_draw_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- THis file will contain the list of items in the navigation draw -->
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"></LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_gravity="left" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Medium Text"
android:id="#+id/textView3"
android:layout_gravity="left"/>
</LinearLayout>
activity_main.xml
<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">
<!-- The main content view which will be a fragment-->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- <LinearLayout
android:id="#+id/header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
-->
<ListView android:id="#+id/left_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="#ffff"/>
<!-- </LinearLayout> -->
</android.support.v4.widget.DrawerLayout>
AdapterClass.java
public class AdapterClass extends BaseAdapter {
private Context context;
private NavigationItem[] navigationItems;
public AdapterClass(Context context, NavigationItem[] items)
{
this.context = context;
navigationItems = items;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (convertView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.navigation_draw_items, parent,false);
}
else
{
row = convertView;
}
TextView tvTitle = (TextView) row.findViewById(R.id.textView3);
ImageView tvImage = (ImageView) row.findViewById(R.id.imageView);
tvTitle.setText(navigationItems[position].stringTitle);
tvImage.setImageResource(navigationItems[position].drawableIcon);
return row;
}
}
NavigationItem.java
public class NavigationItem {
public NavigationItem(int stringTitle, int drawableIcon)
{
this.stringTitle = stringTitle;
this.drawableIcon = drawableIcon;
}
public int stringTitle;
public int drawableIcon;
}
MainActivity.java
public class MainActivity extends Activity implements EditListFragment.OnFragmentInteractionListener {
//private String[] items;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
public void onFragmentInteraction(String id)
{
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
// To do
AdapterClass navigationMenuAdapter;
NavigationItem[] navigationMenuItems = {
new NavigationItem(R.string.cat, R.drawable.cat),
new NavigationItem(R.string.dog, R.drawable.dog),
new NavigationItem(R.string.fish, R.drawable.fish),
};
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
navigationMenuAdapter = new AdapterClass(this, navigationMenuItems);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(navigationMenuAdapter);
mDrawerList.setOnItemClickListener(new DrawItemClickListener());
// Old code
//mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items));
//items = getResources().getStringArray(R.array.items_array);
}
#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);
}
private class DrawItemClickListener implements ListView.OnItemClickListener
{
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectedItem(position);
}
}
private void selectedItem(int position)
{
switch (position)
{
case 0:
//Fragment addList = ItemList
//Fragment addList = new ItemList();
//Bundle args = new Bundle();
//args.putInt(ItemList.LIST_NUMBER, position);
//addList.setArguments(args);
Fragment addList = ItemList.newInstance();
FragmentManager addListFragmentManager = getFragmentManager();
addListFragmentManager.beginTransaction().replace(R.id.content_frame, addList).commit();
//mDrawerLayout.closeDrawer(mDrawerLayout);
break;
case 1:
Fragment editList = EditListFragment.newInstance();
FragmentManager editListFragmentManager = getFragmentManager();
editListFragmentManager.beginTransaction().replace(R.id.content_frame, editList).commit();
break;
case 2:
Fragment deleteList = EditListFragment.newInstance();
FragmentManager deleteListFragmentManager = getFragmentManager();
deleteListFragmentManager.beginTransaction().replace(R.id.content_frame, deleteList).commit();
break;
}
}
}

How to use ViewPager with NavigationDrawer in Android

I am trying to use in the same activity a NavigationDrawer and a ViewPager and it doesn't work correctly. I'm following the developer google tutorial I want to have three tabs, each one will show a different ExpandableList if it was selected. Currently I get the NavigationDrawer and the ExpandableList working fine, however the TabBar and de ViewPager doesn't manage the swipe and click events.
Could anyone help me? I've been reading and searching for ages!!
My main Activity HomeActivity is like this:
public class HomeActivity extends FragmentActivity implements ActionBar.TabListener{
// ExpandableList
private ArrayList<String> parentItems = new ArrayList<>();
private ArrayList<Object> childItems = new ArrayList<>();
// SlideMenu
private String[] mPlanetTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ActionBarDrawerToggle mDrawerToggle;
// Declaraciones Pager
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
///// EXPANDABLELISTVIEW PART /////
ExpandableListView expandableList = (ExpandableListView) findViewById(R.id.expandableListView1);
expandableList.setGroupIndicator(null);
expandableList.setClickable(true);
setGroupParents();
setChildData();
MyExpandableAdapter adapter = new MyExpandableAdapter(parentItems, childItems);
adapter.setInflater((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE), this);
expandableList.setAdapter(adapter);
expandableList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
return false;
}
});
/////// ACTIONBAR PART///////////
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(false);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);
mTitleTextView.setText("Título");
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
/////// NAVIGATION DRAWER PART////////
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.prueba_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
//getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
//getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// if (savedInstanceState == null) {
// selectItem(0);
// }
////////////PART VIEWPAGER///////////////
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
actionBar.setHomeButtonEnabled(false);
// Specify that we will be displaying tabs in the action bar.
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter.
// Also specify this Activity object, which implements the TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_home, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//boolean res = false;
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.add:
Toast.makeText(this, "add element", Toast.LENGTH_LONG).show();
break;
case R.id.search:
Toast.makeText(this, "search a text", Toast.LENGTH_LONG).show();
break;
case R.id.edit:
Toast.makeText(this, "edit a element", Toast.LENGTH_LONG).show();
break;
case R.id.delete:
Toast.makeText(this, "delete a element", Toast.LENGTH_LONG).show();
break;
case R.id.action_settings:
Toast.makeText(this, "acction settings", Toast.LENGTH_LONG).show();
break;
}
return super.onOptionsItemSelected(item);
}
/* The click listner for ListView in the navigation drawer */
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) {
//TODO
switch (position) {
case 0:
Toast.makeText(this, "elemento 0", Toast.LENGTH_LONG).show();
break;
case 1:
Toast.makeText(this, "elemento 1", Toast.LENGTH_LONG).show();
break;
case 2:
Toast.makeText(this, "elemento 2", Toast.LENGTH_LONG).show();
break;
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void setGroupParents() {
parentItems.add("Androwwid");
parentItems.add("Core Java");
parentItems.add("Desktop Java");
parentItems.add("Enterprise Java");
}
public void setChildData() {
// Android
ArrayList<String> child = new ArrayList<>();
child.add("Core");
child.add("Games");
childItems.add(child);
// Core Java
child = new ArrayList<>();
child.add("Apache");
child.add("Applet");
child.add("AspectJ");
child.add("Beans");
child.add("Crypto");
childItems.add(child);
// Desktop Java
child = new ArrayList<>();
child.add("Accessibility");
child.add("AWT");
child.add("ImageIO");
child.add("Print");
childItems.add(child);
// Enterprise Java
child = new ArrayList<>();
child.add("EJB3");
child.add("GWT");
child.add("Hibernate");
child.add("JSP");
childItems.add(child);
}
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new DummySectionFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
return "Section " + (position + 1);
}
}
public static class DummySectionFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_section_dummy, container, false);
Bundle args = getArguments();
// ((TextView) rootView.findViewById(android.R.id.text1)).setText(
// getString(R.string.dummy_section_text, args.getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
My activity_home.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<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">
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:name="com.example.julio.listviewactionbar.Fragment_A"
android:id="#+id/fragment_explist"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/fragment_explistview" />
<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>
</RelativeLayout>
Change your activity_home.xml as follows
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/fragment_explist"
android:name="com.example.julio.listviewactionbar.Fragment_A"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
tools:layout="#layout/fragment_explistview" />
</FrameLayout>
<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>
or
Use ViewPager logic in fragment
Using DrawerLayout as the root element in your xml and ViewPager inside it as the first child should do it . I had the same thing done few days back.
Source - Navigation drawer and view pager in same activity
I think your issue is that the DrawerLayout is stealing touches from the viewpager. When you swipe is the DrawerLayout coming out instead of the viewpager moving?
If this is the case then you need to extend DrawerLayout and ignore touches or extend the viewpager and have it request it's parent not disallow touch events.
Here is an example of what I think you're trying to do but with viewpagers inside viewpagers:
https://github.com/willowtreeapps/OAK/blob/master/oak-demos/src/oak/demo/widget/ParentSwipingViewPagerActivity.java
https://github.com/willowtreeapps/OAK/blob/master/oak-library/src/main/java/oak/widget/ParentSwipingViewPager.java

To implement the navigation drawer in an existing application

I am new to android, I am trying to develop an application. In this application there is a base activity which is extended in all the remaining activities. The main problem is that I want to implement a navigation drawer, I don't know how to implement this without fragments. Can anyone help me to solve this problem.
Thanx
Nina
You can either convert some Activities to Fragments, or you can put the logic for the NavigationDrawer in the BaseActivity.
Check this sample code:
And you can learn more about Navigation Drawers from this link:
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
And for doing it without Fragments I wrote a code below and used ViewPager:
This is my activity_main.xml:
<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">
<!-- Instead of using Fragments I used ViewPager here -->
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:background="#color/list_background"/>
</android.support.v4.widget.DrawerLayout>
This is drawer_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:background="#drawable/list_selector">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toLeftOf="#+id/button_delete_city"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingRight="40dp"
android:textAppearance="?android:attr/textAppearanceListItemSmall"/>
<Button
android:id="#+id/button_delete_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="X" />
</RelativeLayout>
This is NavDrawerListAdapter:
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> navDrawerItems;
MainActivity act;
public NavDrawerListAdapter(Context context, ArrayList<String> navDrawerItems, Activity act){
this.context = context;
this.navDrawerItems = navDrawerItems;
this.act = (MainActivity) act;
}
#Override
public int getCount() {
return navDrawerItems.size();
}
#Override
public Object getItem(int position) {
return navDrawerItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams")
#Override
public View getView(final 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);
Button btn_delete = (Button)convertView.findViewById(R.id.button_delete_city);
btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
act.actionDelete(position);
}
});
}
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
txtTitle.setText(navDrawerItems.get(position));
txtTitle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
act.displayView(position);
}
});
return convertView;
}
public void addItem(String item){
navDrawerItems.add(item);
notifyDataSetChanged();
}
public void removeItem(int position){
navDrawerItems.remove(position);
notifyDataSetChanged();
}
}
And this is my MainActivity:
private ArrayList<String> navDrawerItems;
private NavDrawerListAdapter drawerAdapter;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
//...other codes to implement ViewPager
//...
navDrawerItems = new ArrayList<String>();
// setting the nav drawer list adapter
drawerAdapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems, this);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerList.setAdapter(drawerAdapter);
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) {
// calling onPrepareOptionsMenu() to show action bar icons
}
public void onDrawerOpened(View drawerView) {
// calling onPrepareOptionsMenu() to hide action bar icons
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
public void displayView(int position) {
mPager.setCurrentItem(position, true);
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}

Laggy switching between fragments using a drawerlayout - android

I'm encountering slow/laggy behaviour when swithcing between frgaments using a drawerlayout. I've read up here on stackoverflow and elsewhere regarding solving this issue and a major piece of advice e.g. as seen here is to populating bits of fragment related views elsewhere hence my question of how best can one do the populating part outside of onCreateView() to avoid the laggy behaviour.
Any help is appreciated.
My code is as follows:
My main activity below:
/*! Main activity class */
public class MainActivity extends ActionBarActivity implements FragListener {
/** Private vars */
private DrawerLayout drawerLayout;
private ListView lvDrawerLayout;
private ActionBarDrawerToggle drawerToggle;
private CharSequence drawerTitle;
private CharSequence title;
private DrawerLayoutAdapter drawerLayoutAdapter;
private List<DrawerLayoutDrawer> lvDrawerLayoutData;
/** Public vars */
public static String TAG = "MainActivity";
public MainActivity mainActivity;
public Display display;
public Typeface officialBoldFont, officialRegularFont;
public TextView actionBarTView, tvActionBarTitle = null;
public Fragment fragment;
//!<
public MainActivity() {
}
//!<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// getTitle() is part of Activity
title = drawerTitle = getTitle();
// Obtain the normal device display area
display = getWindowManager().getDefaultDisplay();
// Set official font
officialRegularFont = Typeface.createFromAsset(this.getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(this.getAssets(), "square721extendedbold.ttf");
// Show action bar
getSupportActionBar().show();
// Inflate the custom action bar
LayoutInflater inflator = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mCustomActionView = inflator.inflate(R.layout.actionbar_layout, null);
tvActionBarTitle = (TextView) mCustomActionView.findViewById(R.id.tv_action_bar_title);
tvActionBarTitle.setTypeface(officialBoldFont);
tvActionBarTitle.setTextColor(Color.parseColor("#000000"));
tvActionBarTitle.setTextSize(14.5f);
getSupportActionBar().setCustomView(mCustomActionView);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(0xffFFCC00));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
// Inflate and customise the drawer layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setDrawerShadow(new ColorDrawable(0xffFF0000), GravityCompat.START);
drawerLayout.setBackgroundResource(R.drawable.bgnd_drawerlayout_default);
drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_closed) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(title);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(drawerToggle);
// Inflate and customise the drawer layout list and drawer layout adapter
lvDrawerLayout = (ListView) findViewById(R.id.lv_drawer);
lvDrawerLayout.setDividerHeight(2);
// Below is the listview's bgnd and is different from bgnd_lv_item_drawerlayout.xml which is the bgnd for the items in this LV
lvDrawerLayout.setBackgroundResource(R.drawable.bgnd_lv_drawerlayout_default);
lvDrawerLayoutData = new ArrayList<DrawerLayoutDrawer>();
lvDrawerLayoutData.add(new DrawerLayoutDrawer("ADMINISTRATION", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("FINANCE CALCULATOR", R.drawable.ic_test));
lvDrawerLayoutData.add(new DrawerLayoutDrawer("EXIT", R.drawable.ic_test));
drawerLayoutAdapter = new DrawerLayoutAdapter(this, R.layout.lv_layout_drawer, lvDrawerLayoutData, officialRegularFont, officialBoldFont);
lvDrawerLayout.setAdapter(drawerLayoutAdapter);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Call starting fragment
if (savedInstanceState == null) {
callStartingFrag(0);
}
}
//!< Call starting fragment
public void callStartingFrag(int position) {
Bundle args = new Bundle();
fragment = new FragmentOne();
args.putString(" ", lvDrawerLayoutData.get(position).getItemName());
args.putInt(" ", lvDrawerLayoutData.get(position).getImgResID());
fragment.setArguments(args);
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
//!< Enable drawer layout
public void enableDrawerLayout() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
//!< Set custom action bar title
public void setActionBarTitle(String title){
tvActionBarTitle.setText(title);
}
//!< Return MainActivity object
public MainActivity getMainActivity() {
mainActivity = new MainActivity();
return mainActivity;
}
//!< This hook is called whenever an item in your options menu is selected. . The action bar home/up action should open or close the drawer. ActionBarDrawerToggle will take care of this.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
//!< Sync the toggle state after onRestoreInstanceState has occurred. Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
//!< Pass any configuration change to the drawer toggles. This method should always be called by your Activity's onConfigurationChanged method.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
//!< Call respective fragment
public void selectItem(int position) {
switch (position) {
case 0:
fragment = new FragmentTwo();
break;
case 1:
fragment = new FragmentThree();
break;
case 2:
finish();
break;
default:
break;
}
FragmentManager frgManager = getFragmentManager();
frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
lvDrawerLayout.setItemChecked(position, true);
drawerLayout.closeDrawer(lvDrawerLayout);
}
}
Drawer layout code:
<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="fill_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ListView
android:id="#+id/lv_drawer"
android:layout_width="240dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#000000"/>
</android.support.v4.widget.DrawerLayout>
Drawer layout listview laout code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
android:id="#+id/itemLayout">
<TextView
android:id="#+id/tv_itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</LinearLayout>
Action bar layout code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/transparent" >
<TextView
android:id="#+id/tv_action_bar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:textSize="15dp"
android:maxLines="1"
android:ellipsize="end"/>
</RelativeLayout>
1st fragment code:
public class FragmentOne extends Fragment {
ImageView ivIcon;
TextView tvAgentID;
public Typeface officialBoldFont, officialRegularFont;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentOne() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout_one, container, false);
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag one list item 1", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragOneClickListener());*/
//
officialRegularFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedreg.ttf");
officialBoldFont = Typeface.createFromAsset(getActivity().getAssets(), "square721extendedbold.ttf");
tvAgentID = (TextView) view.findViewById(R.id.tv_agentid);
tvAgentID.setText("TESTING 1 2 3");
tvAgentID.setTypeface(officialBoldFont);
tvAgentID.setTextColor(Color.BLACK);
tvAgentID.setBackgroundColor(Color.WHITE);
tvAgentID.setTextSize(25f);
return view;
}
}
1st fragment layout XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ll_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#000000">
<LinearLayout
android:id="#+id/ll_innerloginlayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="20dp"
android:padding="20dp">
<TextView
android:id="#+id/tv_agentid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
</LinearLayout>
2nd fragment code below:
public class FragmentTwo extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
private List<DrawerLayoutDrawer> dataList;
public FragmentTwo()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_two, container, false);
//
((MainActivity) getActivity()).setActionBarTitle("Test screen 2");
((MainActivity) getActivity()).enableDrawerLayout();
/*dataList = new ArrayList<DrawerLayoutDrawer>();
dataList.add(new DrawerLayoutDrawer("Frag two list item 2", R.drawable.lv_tempimg2));
((MainActivity) getActivity()).changeDrawerList(dataList, new FragTwoClickListener());*/
ivIcon=(ImageView)view.findViewById(R.id.frag2_icon);
tvItemName=(TextView)view.findViewById(R.id.frag2_text);
tvItemName.setText("TESTING FRAG TWO");
tvItemName.setTextSize(45f);
tvItemName.setTextColor(Color.RED);
tvItemName.setBackgroundColor(Color.BLACK);
return view;
}
}
2nd fragment XML code:
<?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="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag2_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag2_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:layout_marginLeft="200dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="12dp"
android:paddingBottom="0dp"/>
</LinearLayout>
3rd fragment code:
public class FragmentThree extends Fragment {
ImageView ivIcon;
TextView tvItemName;
public static final String IMAGE_RESOURCE_ID = "iconResourceID";
public static final String ITEM_NAME = "itemName";
public FragmentThree()
{
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_layout_three, container, false);
ivIcon=(ImageView)view.findViewById(R.id.frag3_icon);
tvItemName=(TextView)view.findViewById(R.id.frag3_text);
tvItemName.setText("TESTING FRAG THREE");
return view;
}
}
3rd fragment XML code:
<?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="horizontal"
>
<!--
**************************IMPORTANT***********************************
change this id attribute values as "frag2_icon" and "frag2_text" for
fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
fragment_layout_three.xml
**********************************************************************
-->
<ImageView
android:id="#+id/frag3_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/frag3_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
1st fragment listener:
public class FragOneClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragOneSelectItem(position);
}
}
2nd fragment listener:
public class FragTwoClickListener implements ListView.OnItemClickListener {
MainActivity mainActivity;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mainActivity = new MainActivity();
mainActivity.fragTwoSelectItem(position);
}
}

show a blank screen when selecting a fragment for the second time

In my application, I have used the SherlockNavigationDrawer. By default, the navigationDrawer has 3 menu to opens 3 fragments. I have modified one of the following fragment. But when click for the second time on the menu of my fragment, screen not display anything! The first time, no problem; But the second time, a blank page is displayed.
In this case, if click on the default fragment menu in NavigationDrawer and then click on my fragment on the screen comes back on, but if click on my fragment menu again, screen show a blank page!
Also i have shown in my fragment a list of items, that by click on each item replace new fragment that show details of the specific item. but detail fragment is a display that is empty!!!
Friends! Where is the problem?
MainActivity Code:
public class ActivityMain extends SherlockFragmentActivity {
// Declare Variables
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment_categorylist = new Fragment_CategoryList();
private CharSequence mDrawerTitle;
private CharSequence mTitle;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from drawer_main.xml
setContentView(R.layout.drawer_main);
// Get the Title
mTitle = mDrawerTitle = getTitle();
// Generate title
title = new String[] { getString(R.string.TitleFragment1),
getString(R.string.TitleFragment2),
getString(R.string.TitleFragment3) };
// Generate subtitle
subtitle = new String[] { getString(R.string.SubtitleFragment1),
getString(R.string.SubtitleFragment2),
getString(R.string.SubtitleFragment3) };
// Generate icon
icon = new int[] { R.drawable.action_about, R.drawable.action_settings,
R.drawable.collections_cloud };
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
mDrawerList = (ListView) findViewById(R.id.listview_drawer);
// Set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
ActivitySwipeDetector swipe = new ActivitySwipeDetector(this);
DrawerLayout swipe_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
swipe_layout.setOnTouchListener(swipe);
//LinearLayout swipe_layout2 = (LinearLayout) findViewById(R.id.fragment_pager_layout);
//swipe_layout2.setOnTouchListener(swipe);
// Pass string arrays to MenuListAdapter
mMenuAdapter = new MenuListAdapter(ActivityMain.this, title, subtitle,
icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture listview menu item click
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// Enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
// TODO Auto-generated method stub
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
// Set the title on the action when drawer open
getSupportActionBar().setTitle(mDrawerTitle);
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// ListView click listener in the navigation drawer
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) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Locate Position
switch (position) {
case 0:
ft.replace(R.id.content_frame, fragment1);
break;
case 1:
ft.replace(R.id.content_frame, fragment2);
break;
case 2:
ft.replace(R.id.content_frame, fragment_categorylist);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Get the title followed by the position
setTitle(title[position]);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
Default Fragment Code:
public class Fragment3 extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment3, container, false);
return rootView;
}
}
My Fragment (Modified Fragment) :
public class Fragment_CategoryList extends SherlockFragment {
static final int NUM_ITEMS = 1;
MyAdapter mAdapter;
ViewPager mPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pager, container,
false);
mAdapter = new MyAdapter(getSherlockActivity().getSupportFragmentManager());
mPager = (ViewPager) rootView.findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
// Watch for button clicks.
Button button = (Button) rootView.findViewById(R.id.goto_first);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(0);
}
});
button = (Button) rootView.findViewById(R.id.goto_last);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mPager.setCurrentItem(NUM_ITEMS - 1);
}
});
return rootView;
}
// ////////////////////////////////////////////////////////////////////////
public static class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return NUM_ITEMS;
}
#Override
public Fragment getItem(int position) {
return ArrayListFragment.newInstance(position);
}
}
public static class ArrayListFragment extends SherlockListFragment {
int mNum;
/**
* Create a new instance of CountingFragment, providing "num" as an
* argument.
*/
static ArrayListFragment newInstance(int num) {
ArrayListFragment f = new ArrayListFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
/**
* When creating, retrieve this instance's number from its arguments.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
/**
* The Fragment's UI is just a simple text view showing its instance
* number.
*/
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_pager_list, container,
false);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Fragment #" + mNum);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// setListAdapter(new ArrayAdapter<String>(getActivity(),
// android.R.layout.simple_list_item_1, Cheeses.sCheeseStrings));
DBAdapter db = new DBAdapter(getActivity());
// Create an array to specify the fields we want to display in the
// list (only TITLE)
String[] from = new String[] { "title", "_id" };
// and an array of the fields we want to bind those fields to (in
// this case just text1)
int[] to = new int[] { R.id.entry1, R.id.entry2 };
ArrayList<HashMap<String, String>> categoryList = db.getAll();
if (categoryList.size() != 0) {
ListAdapter adapter = new SimpleAdapter(getActivity(),
categoryList,
R.layout.fragment_pager_list_entry, from, to);
setListAdapter(adapter);
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
final FragmentTransaction ft = getSherlockActivity().getSupportFragmentManager().beginTransaction();
Fragment myFragment = new Fragment_QA();
int idplus = (int)id + 1;
Bundle args = new Bundle();
args.putLong("cid", idplus);
//myFragment.setArguments(args);
ft.replace(((ViewGroup)(getView().getParent())).getId(), myFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
}
Main Activity UI:
<android.support.v4.widget.DrawerLayout
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" />
<ListView
android:id="#+id/listview_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" />
My Fragment UI (Fragment_CategoryList):
<LinearLayout
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
</android.support.v4.view.ViewPager>
<LinearLayout android:orientation="horizontal"
android:gravity="center" android:measureWithLargestChild="true"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_weight="0">
<Button android:id="#+id/goto_first"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="FIRST">
</Button>
<Button android:id="#+id/goto_last"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="LAST">
</Button>
</LinearLayout>
I don't know if this question is still available but for someone could be a helpful answer.
That's what you should do :
change from
android.support.v4.app.FragmentPagerAdapter to android.support.v4.app.FragmentStatePagerAdapter
try to change getSupportFragmentManager to getChildFragmentManager

Categories

Resources