(FRAGMENT) UPDATE LISTVIEW WHEN I CLICK FRAGMENT MENU - android

if i delete item/s on listview and then i click the home menu in navigation drawer the listview won't update.
here's my mainactivity
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navLogout;
String[] navMenuTitles;
TypedArray navMenuIcons;
ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(
R.array.nav_drawer_items_not_login);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons
.getResourceId(0, -1)));
// login
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons
.getResourceId(1, -1)));
// register
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons
.getResourceId(2, -1)));
// classic brownies
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons
.getResourceId(3, -1)));
// cupcakes
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons
.getResourceId(3, -1)));
// cookies
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons
.getResourceId(3, -1)));
// feedback
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons
.getResourceId(4, -1)));
// about
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons
.getResourceId(5, -1)));
// Recycle the typed array
navMenuIcons.recycle();
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);
}
}
/**
* Slide menu item click listener
* */
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;
}
Fragment fragment = null;
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_search:
Toast.makeText(this, "search selected", Toast.LENGTH_SHORT).show();
break;
case R.id.action_shoppingcart:
Toast.makeText(this, "shopping cart selected", Toast.LENGTH_SHORT)
.show();
fragment = new FeedbackFragment();
return true;
default:
break;
}
return true;
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_search).setVisible(!drawerOpen);
menu.findItem(R.id.action_shoppingcart).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new LoginFragment();
break;
case 2:
fragment = new RegisterFragment();
break;
case 3:
fragment = new ClassicBrowniesFragment();
break;
case 4:
fragment = new CupcakesFragment();
break;
case 5:
fragment = new CookiesFragment();
break;
case 6:
fragment = new FeedbackFragment();
break;
case 7:
fragment = new AboutFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#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);
// 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);
}
}
here's my HomeFragment
_just asking question, using some more words to describe your problem will always help. If there are really nothing more to say.
public class HomeFragment extends Fragment implements OnItemClickListener {
String[] member_names;
TypedArray product_icons;
String[] statues;
String[] contactType;
List<RowItem> rowItems;
ListView mylistview;
CustomAdapter myadapter;
CustomAdapter newadapter;
public HomeFragment() {
}
View rootView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_home, container,
false);
rowItems = new ArrayList<RowItem>();
member_names = getResources().getStringArray(R.array.Member_names);
product_icons = getResources().obtainTypedArray(R.array.product_icons);
statues = getResources().getStringArray(R.array.statues);
for (int i = 0; i < member_names.length; i++) {
RowItem item = new RowItem(member_names[i],
product_icons.getResourceId(i, -1), statues[i]);
rowItems.add(item);
}
mylistview = (ListView) rootView.findViewById(R.id.list);
CustomAdapter adapter = new CustomAdapter(getActivity(), rowItems);
mylistview.setAdapter(adapter);
product_icons.recycle();
mylistview.setOnItemClickListener(this);
mylistview.setScrollingCacheEnabled(false);
mylistview.invalidateViews();
return rootView;
}
public void updateList(ArrayAdapter adapter){
mylistview = (ListView)rootView.findViewById(R.id.list);
mylistview.setAdapter(adapter);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String member_name = rowItems.get(position).getMember_name();
int product_icons = rowItems.get(position).getProfile_pic_id();
String status = rowItems.get(position).getStatus();
RowItem item = rowItems.get(position);
Intent intent = new Intent(getActivity().getApplicationContext(),
FeedbackFragment.class);
intent.putExtra(member_name, item.getMember_name());
intent.putExtra(status, item.getStatus());
rowItems.remove(item);
newadapter = new CustomAdapter(getActivity(), rowItems);
mylistview.setAdapter(newadapter);
newadapter.notifyDataSetChanged();
Toast.makeText(getActivity().getApplicationContext(),
"Added to Cart: " + member_name, Toast.LENGTH_SHORT).show();
}
}

You seem to have a logical issue here. You are removing the item and updating the listView, which is correct, but you are not changing the actual List List<RowItem> rowItems; beyond the current scope. When you select HomeFragment again, you are creating a new instance and everything resets.
One solution might be to pass the data from the updated List<RowItem> rowItems; to the next Fragment so that the changes you made are reflected in other Fragments.
Currently, you create your List<RowItem> rowItems by piecing together the following:
member_names = getResources().getStringArray(R.array.Member_names);
product_icons = getResources().obtainTypedArray(R.array.product_icons);
statues = getResources().getStringArray(R.array.statues);
However, when you remove the RowItem from the list, you don't change any of those three variables. Thus, when the new instance of the Fragment is initialized, you create a brand new List of RowItems using the same old data.
In short, here are two possible solutions:
Update the variables member_names, product_icons, statues when you remove the item from the list
Pass the List of RowItem between the Fragments

Related

Navigation Drawer With Checkboxs

**I Put Checkbox in Navigation View and want to get the position Of true checkbox ,But when i click no checkbox its display only true and false .
I need checkx position in Listview Item Click Event .
I Done Almoast Xml Code , also call checkbox click event in customAdaptor
But Can't Find Main Activity Code .
get position of Checkbox when its checked true in navigation drawer?
**
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1),true));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1),true));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1),true));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1),true));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1), true));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1), true));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1), true));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1), true));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[10], navMenuIcons.getResourceId(10, -1), true));
// Recycle the typed array
navMenuIcons.recycle();
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
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_drawer);
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) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().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);
}
}
/**
* Slide menu item click listener
* */
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
NavDrawerItem navDrawerItem = (NavDrawerItem) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),navDrawerItem.getTitle(),Toast.LENGTH_LONG).show();
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.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);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
}
}
this is my adapter
#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);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
final CheckBox ch = (CheckBox) convertView.findViewById(R.id.checkBox);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
ch.setSelected(navDrawerItems.get(position).getCounterVisibility());
ch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean ans = ch.isChecked();
navDrawerItems.get(position).setCounterVisibility(ans);
Toast.makeText(context,String.valueOf(ch.isChecked()),Toast.LENGTH_LONG).show();
}
});
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
}else{
// hide the counter view
}
return convertView;
}
Define one Interface class:
public Interface OnChckBoxClickListener
{
public void onCheckBoxClick(int position, boolean isChecked);
}
After that create object of interface in adapter, see following code:
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems, new OnCheckBoxClickLisener()
{
public void OnCheckBoxClick(int position, boolean isChecked)
{
//print here position and isChecked
// also do here code what you want
}
});
After that registered listener in constructor of adapter:
public NavDrawerListAdapter(Context conext, ArrayList<NavDrawerItem> navDrawerItems, OnCheckBoxClickLisener listener)
{
this.context = context;
this.navDrawerItems = navDrawerItems;
this.lisetner = listener;
}
Then set Listener to OnClickOfCheckBox in getView:
ch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean ans = ch.isChecked();
//navDrawerItems.get(position).setCounterVisibility(ans);
listener.OnCheckBoxClick(position, ans);
Toast.makeText(context,String.valueOf(ch.isChecked()),Toast.LENGTH_LONG).show();
}
});

getArguments return null

I need to transfer arraylist from one fragment to another. I looked at a few articles with the same problem, but not one of the options could not solve my problem....
From BakeFragment
OrderFragment orderFragment = new OrderFragment();
Bundle bundle = new Bundle();
bundle.putStringArrayList(ORDER_KEY, orderList);
orderFragment.setArguments(bundle);
I need to get this arraylist in OrderFragment. How i try to do it
First version
Bundle mBundle = this.getArguments();
orderArrayList = mBundle.getStringArrayList(ORDER_KEY);
Error :
java.lang.NullPointerException
at com.zhisheng.navdrawer.model.OrderFragment.onCreateView(OrderFragment.java:38)
at android.app.Fragment.performCreateView(Fragment.java:1699)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
at android.app.BackStackRecord.run(BackStackRecord.java:682)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5137)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
at dalvik.system.NativeStart.main(Native Method)
Second version
if(getArguments()!=null){
orderArrayList = this.getArguments().getStringArrayList("key");
}
Don't get an error, but nothing happens.
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[10], navMenuIcons.getResourceId(10, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[11], navMenuIcons.getResourceId(11, -1)));
// Recycle the typed array
navMenuIcons.recycle();
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
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
displayView(11);
}
}
/**
* Slide menu item click listener
*/
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:
displayView(11);
//Toast.makeText(getApplicationContext(), "RasRas", Toast.LENGTH_LONG).show();
return true;
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new BakeFragment();
break;
case 1:
fragment = new GarnishFragment();
break;
case 2:
fragment = new HotDishesFragment();
break;
case 3:
fragment = new DesertsFragment();
break;
case 4:
fragment = new HomeFragment();
break;
case 5:
fragment = new SnacksFragment();
break;
case 6:
fragment = new DrinkFragment();
break;
case 7:
fragment = new PizzaFragment();
break;
case 8:
fragment = new SaladFragment();
break;
case 9:
fragment = new ConfectionFragment();
break;
case 10:
fragment = new SoupFragment();
break;
case 11:
fragment = new OrderFragment();
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
}
BakeFragment
public class BakeFragment extends Fragment {
final static String ORDER_KEY="key";
String myString;
ListView listView;
ArrayList<MenuItem> arrayList;
CustomAdapter customAdapter;
MenuItem menuItem;
ArrayList<String> orderList;
View rootView = null;
Integer[] quantity = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
String[] bakeList = new String[]{
"Булочка с кунжутом", "Ватрушка с творогом", "Качори с чечевицей", "Лепешка \"Пападам\"",
"Лепешка \"Паратха\"", "Лепешка \"Чапати\"", "Лепешка с сыром", "Пирожное \"Корзиночка\"",
"Пирожок с капустой", "Пирожок с картофелем", "Пряник кокосовый экадашный" , "Самоса с вишней",
"Самоса с клубникой", "Самоса с малиной","Самоса с овощами и паниром", "Самоса с сухофруктами (печеная)", "Самоса с творогом", "Самоса с черной смородиной",
"Самоса с яблоком в карамели"
};
Integer[] imagesOfBakeList = new Integer[]{
R.drawable.bake1, R.drawable.bake2, R.drawable.bake3, R.drawable.bake4, R.drawable.bake5,
R.drawable.bake6, R.drawable.bake7, R.drawable.bake8, R.drawable.bake9, R.drawable.bake10,
R.drawable.bake11, R.drawable.bake12, R.drawable.bake13, R.drawable.bake14, R.drawable.bake15,
R.drawable.bake16, R.drawable.bake17, R.drawable.bake18, R.drawable.bake19
};
String[] priceOfBakeList = new String[]{
"30", "60", "60", "30", "70", "30", "70", "90", "60", "60", "60", "60", "60", "60", "60", "60",
"60", "60", "60"
};
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.list_item, container, false);
listView = (ListView)rootView.findViewById(R.id.list_of_menu_item);
orderList = new ArrayList<String>();
arrayList = new ArrayList<MenuItem>();
for(int i = 0; i < bakeList.length; i++) {
menuItem = new MenuItem(imagesOfBakeList[i], bakeList[i], priceOfBakeList[i]);
arrayList.add(menuItem);
}
customAdapter = new CustomAdapter(getActivity().getApplicationContext(), arrayList);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
View v = null;
#Override
public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
//Toast.makeText(getActivity().getApplicationContext(), "Вы заказали " + customAdapter.getItem(position), Toast.LENGTH_SHORT).show();
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflater.inflate(R.layout.view, null);
String dishForOrderList;
final int s = customAdapter.getPrice(position);
final String dish = customAdapter.getItem(position).toString();
final String allstr;
Spinner spinner = (Spinner) v.findViewById(R.id.spinView);
final TextView orderText = (TextView) v.findViewById(R.id.order_text);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.option, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selected = parent.getSelectedItem().toString();
int t = Integer.parseInt(selected);
myString = dish + " x" + t + " " + (s * t);
String abc = dish+" x"+t+" !";
orderText.setText(myString);
Toast.makeText(getActivity(), myString, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(v);
builder.setTitle("Сколько порций " + dish + " вы хотите заказать?");
builder.setCancelable(false);
builder.setNegativeButton("Заказать", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
orderList.add(myString);
Toast.makeText(getActivity(), orderList+"", Toast.LENGTH_LONG).show();
OrderFragment orderFragment = new OrderFragment();
Bundle bundle = new Bundle();
bundle.putStringArrayList(ORDER_KEY, orderList);
orderFragment.setArguments(bundle);
dialog.cancel();
}
});
builder.setPositiveButton("Отмена", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
return rootView;
}
}
OrderFragment
public class OrderFragment extends Fragment {
View rootView = null;
ListView orderListView;
ArrayList<String> orderArrayList;
ArrayAdapter<String> stringArrayAdapter;
final static String ORDER_KEY="key";
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.order_list, container, false);
orderArrayList = new ArrayList<String>();
Bundle mBundle = this.getArguments();
orderArrayList = mBundle.getStringArrayList(ORDER_KEY);
/* if(getArguments()!=null){
orderArrayList = this.getArguments().getStringArrayList("key");
}*/
// orderArrayList = this.getArguments()!=null? getArguments().getStringArrayList("array") : null;
//Toast.makeText(getActivity(), "d = "+orderArrayList, Toast.LENGTH_LONG).show();
// orderArrayList = bundle.getStringArrayList("key");
orderListView = (ListView)rootView.findViewById(R.id.order_list_view);
stringArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, orderArrayList);
orderListView.setAdapter(stringArrayAdapter);
return rootView;
}}
I think your problem can be traced to this block of code:
public void onClick(DialogInterface dialog, int which) {
orderList.add(myString);
Toast.makeText(getActivity(), orderList+"", Toast.LENGTH_LONG).show();
OrderFragment orderFragment = new OrderFragment();
Bundle bundle = new Bundle();
bundle.putStringArrayList(ORDER_KEY, orderList);
orderFragment.setArguments(bundle);
dialog.cancel();
}
You are trying to create an OrderFragment as a result of the dialog button being clicked. However, since you are not attaching this instance to the activity, the arguments are never set. In the displayView() method you have this:
case 11:
fragment = new OrderFragment();
Basically, the fragment that you have doesn't have any arguments set - this is why you can't see them afterwards.
To deal with this, I can suggest you take a couple of steps:
Implement a proper fragment - fragment communication. Bear in mind that fragments should never communicate directly to one another (except if they are nested, but this is not your case). It would be better if you organize this through the activity - BakeFragment gets the orders, sends them to the activity and the activity sets them as arguments of the OrderFragment. You can get a nice example and more info on this approach here: http://developer.android.com/training/basics/fragments/communicating.html
Reorganize your displayView() method. Currently, you are going to force the creation of a new instance of the desired fragment each time you invoke this method. This can lead to undesired behavior - poor performance, strange state of the back stack, etc. Further more, you won't be able to benefit from the automatic saving of fragment parameters when fragments get recreated. I suggest you make use of tags and firstly check if the fragment, you want to show, is already there.
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findByTag(THE_FRAGMENT_TAG);
if (fragment == null) {
// logic to create a fragment instance
}
// logic to show the fragment
The only time I see your OrderFragment used in a FragmentTransaction is when it is created in your MainActivity displayView method. There, it has no arguments set on it.
Your BakeFragment does create an OrderFragment and set its arguments, but it is never added through a FragmentTransaction and goes out of scope as soon as your onClick(DialogInterface dialog, int which) method is done executing. Therefore the OrderFragment with arguments set is never used.
Did you mean to show this fragment to the user through the use of a FragmentTransaction? If so, you could have BakeFragment define an interface with a method that indicates to the listener that the user either decided to create an order or cancelled. Have MainActivity implement this interface and register itself as a listener on your BakeFragment.
PS: Why is your logic seemingly reversed with your AlertDialog negative and positive button click handlers?

Navigation Drawer with header, indexOutOfBoundsException: length=9; index=9

I have Navigation Drawer and all is ok. but i want add header. In this case i receive this error when i clicked in the Last element of the drawer.
java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
this is my main code:
super.onCreate(savedInstanceState);
setContentView(R.layout.main);{
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
//Drawer Layout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//Drawer list
mDrawerList = (ListView) findViewById(R.id.main_list_slidermenu);
//Drawer header image
View header=getLayoutInflater().inflate(R.layout.drawer_header, null);
//Establecemos el header
mDrawerList.addHeaderView(header);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Avisos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Instalaciones
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Buscar por Localización
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Buscar por Actividad
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// Buscar por Espacios
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// Buscar por Horarios
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
// Favoritos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
// Configuración
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(5, -1)));
//navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
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();
}
};
//mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
and SlideMenuClickListener implements ListView.OnItemClickListener and lauch displayView method.
displayView method code this is:
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
//Do nothing. Because this is image
break;
case 1:
fragment = new HomeFragment();
break;
case 2:
fragment = new RssAvisosFragment();
break;
case 3:
fragment = new TodasLasInstalacionesFragment();
break;
case 4:
fragment = new BuscarInstalacionesDistanciaFragment();
break;
case 5:
fragment = new BuscarInstalacionesActividadFragment();
break;
case 6:
fragment = new PagesFragment();
break;
case 7:
fragment = new BuscarInstalacionesHorarioFragment();
break;
case 8:
fragment = new FavoritosInstalacionesFragment();
break;
case 9:
fragment = new PreferenceFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.main_frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
Edit
This is NavDrawerListAdapter code:
public class NavDrawerListAdapter extends BaseAdapter{
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#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;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.drawerlist_item, null);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.drawerlist_item_icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.drawerlist_item_title);
TextView txtCount = (TextView) convertView.findViewById(R.id.drawerlist_item_counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
}
Edit
SlideMenuClickListener code is:
/**
* Slide menu item click listener
* */
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);
}
}
Solved.
The error is in this line (displayVIew method):
setTitle(navMenuTitles[position])
Solution is:
setTitle(navMenuTitles[position-1])

Making first list item bigger than remaining items in Navigation Bar

I am having a navigation drawer working fine and it get displayed like this :
Now I want A profile picture of person at top like in google plus :
I had taken the help from http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
But am not able to understand how to modify the xml such that I can make the uppermost list item with more height than remaining items of the list.
Please help.
EDIT : Here is the MainActivity.java
Assuming I am having NavDrawerListAdapter.java and NavDrawerItem.java also
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
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);
}
}
/**
* Slide menu item click listener
* */
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);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FindPeopleFragment();
break;
case 2:
fragment = new PhotosFragment();
break;
case 3:
fragment = new CommunityFragment();
break;
case 4:
fragment = new PagesFragment();
break;
case 5:
fragment = new WhatsHotFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#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);
// 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);
}
}
Seeing the comment here is getView method .Now what should i do next ?
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);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
TextView txtCount = (TextView) convertView.findViewById(R.id.counter);
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
// displaying count
// check whether it set visible or not
if(navDrawerItems.get(position).getCounterVisibility()){
txtCount.setText(navDrawerItems.get(position).getCount());
}else{
// hide the counter view
txtCount.setVisibility(View.GONE);
}
return convertView;
}
xml for header :
<?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="100dp"
android:background="#drawable/list_selector">
<ImageView
android:id="#+id/icon"
android:layout_width="25dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:contentDescription="#string/desc_list_item_icon"
android:src="#drawable/ic_home"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/icon"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#color/list_item_title"
android:gravity="center_vertical"
android:paddingRight="40dp"/>
</RelativeLayout>
Only one thing comes to mind seeing this. ListView headers. Make diffrent Layout for header, inflate it and then set it to your listview
LayoutInflater inflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.my_header_layout, null);
mDrawerList.addHeaderView(view);
While inflating header you can set OnClickListener if you need one

Drawer items Selected effect in android

Overview::
I have a navigation drawer
I am setting the textView color in the adapter when position is 0
to red
On selecting different element in the list that textView is set to
red and others to black
So at anytime only one textview must be set in red(selected
adapter) others in black
Also to note that the reason i am setting red for textview in
adapter when position is o because since its the first fragment shown when it is loaded for the first time
This must be un-selected when i am selecting other adapter which is not
happening
Code i use is::
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);
setNavDrawerItemNormal();
title=(TextView) view.findViewById(R.id.title);
title.setTextColor(getApplicationContext().getResources().getColor(R.color.red));
}
}
public void setNavDrawerItemNormal()
{
for (int i=0; i< mDrawerList.getChildCount(); i++)
{
View v = mDrawerList.getChildAt(i);
TextView txtview = ((TextView) v.findViewById(R.id.title));
txtview.setTextColor(getApplicationContext().getResources().getColor(R.color.black));
}
}
MainActivity.java
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private GridView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (GridView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Home
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
// Find People
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Photos
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Communities, Will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1), true, "22"));
// Pages
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
// What's hot, We will add a counter here
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1), true, "50+"));
// Recycle the typed array
navMenuIcons.recycle();
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);
}
}
/**
* Slide menu item click listener
* */
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);
setNavDrawerItemNormal();
title=(TextView) view.findViewById(R.id.title);
title.setTextColor(getApplicationContext().getResources().getColor(R.color.red));
}
}
public void setNavDrawerItemNormal()
{
for (int i=0; i< mDrawerList.getChildCount(); i++)
{
View v = mDrawerList.getChildAt(i);
TextView txtview = ((TextView) v.findViewById(R.id.title));
txtview.setTextColor(getApplicationContext().getResources().getColor(R.color.black));
}
}
#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);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
* */
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new HomeFragment();
break;
case 1:
fragment = new FragmentOne();
break;
case 2:
fragment = new FragmentTwo();
break;
case 3:
fragment = new FragmentThree();
break;
case 4:
fragment = new FragmentFour();
break;
case 5:
fragment = new FragmentFive();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#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);
// 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);
}
}
NavDrawerListAdapter.java
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#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;
}
#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);
}
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
if (position == 0)
{
txtTitle.setTextColor(context.getResources().getColor(R.color.red));
}
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
NOTE:: I Can achieve my objective with application variable, but i am trying to do without it, programatically
The main idea that You don't need to have any additional variables in adapter / activity, because Android component already have one for lists with single choice. The following solution works fine in your case:
Assume your layout (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 -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<GridView android:id="#+id/list_slidermenu"
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="#111"/>
</android.support.v4.widget.DrawerLayout>
Please note android:choiceMode="singleChoice" - that property will let the list track selected item by itself.
Remove all color setting code from the activity. Instead, use setChecked() to let the list know which item is selected:
public class MainActivity extends ActionBarActivity {
private static final String TAG = "MainActivity";
private DrawerLayout mDrawerLayout;
private GridView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private TextView title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (GridView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setItemChecked(0, true); // NOTE: Set 0 item as checked!
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,
android.R.drawable.ic_input_delete, //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);
}
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
displayView(position);
// NOTE: new item is checked now
mDrawerList.setItemChecked(position, true);
}
}
...
}
In the adapter - just check if item is checked or not and set corresponding test color:
public class NavDrawerListAdapter extends BaseAdapter {
private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
public NavDrawerListAdapter(Context context, ArrayList<NavDrawerItem> navDrawerItems){
this.context = context;
this.navDrawerItems = navDrawerItems;
}
#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;
}
#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);
}
// TODO: Here ViewHolder pattern can be used or
ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
// NOTE: check which item is Checked an set corresponding text color
if (((GridView)parent).isItemChecked(position)) {
txtTitle.setTextColor(context.getResources().getColor(R.color.red));
} else {
txtTitle.setTextColor(context.getResources().getColor(R.color.black));
}
imgIcon.setImageResource(navDrawerItems.get(position).getIcon());
txtTitle.setText(navDrawerItems.get(position).getTitle());
return convertView;
}
}
With above code, text color will be changed only after pointer up (when you press item it's color will still hold old value). If you need it to change color during pressed state, then use the following code in the adapter:
// NOTE: check which item is Checked an set corresponding text color
if (((GridView)parent).isItemChecked(position)) {
//txtTitle.setTextColor(context.getResources().getColor(R.color.red));
txtTitle.setTextColor(context.getResources().getColorStateList(R.color.red_selector));
} else {
//txtTitle.setTextColor(context.getResources().getColor(R.color.black));
txtTitle.setTextColor(context.getResources().getColorStateList(R.color.black_selector));
}
And provide color/red_selector.xml and color/black_selector.xml. E.g. color/black_selector.xml should look the following way:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="#color/red"/>
<item android:color="#color/black"/>
</selector>

Categories

Resources