I've implemented ActionBarDrawerToggle for NavigationDrawer and also used ActionBar.
How can I handle both click events because both require onOptionsItemSelected(MenuItem item) method?
Is there any other way around?
public class A1 extends AppCompatActivity implements OnItemClickListener {
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter < String > adapter;
ActionBarDrawerToggle drawListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a1);
menu = new String[] {
"Home", "Android", "Windows", "Linux", "Raspberry Pi", "WordPress", "Videos", "Contact Us"
};
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
dList = (ListView) findViewById(R.id.left_drawer);
adapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, menu);
dList.setAdapter(adapter);
dList.setOnItemClickListener(this);
dList.setSelector(android.R.color.holo_blue_dark);
drawListener = new ActionBarDrawerToggle(this, dLayout, R.drawable.ic_draw, R.string.dopen) {
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Menu");
}
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
super.onDrawerClosed(drawerView);
}
};
dLayout.setDrawerListener(drawListener);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public boolean onCreateOptionsMenu(Menu menu) //for actionbar
{
getMenuInflater().inflate(R.menu.actionbar, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.copy:
return showToast("Copy");
default:
return false;
}
// if(drawListener.onOptionsItemSelected(item))
// {
// return true;
// }
// return super.onOptionsItemSelected(item);
}
public boolean showToast(String message) {
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
return true;
}
#Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawListener.onConfigurationChanged(newConfig);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawListener.syncState();
}
#Override
public void onItemClick(AdapterView <? > arg0, View v, int position, long id) {
selectitem(position);
dLayout.closeDrawers();
Bundle args = new Bundle();
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
}
public void selectitem(int position) {
dList.setItemChecked(position, true);
setTitle(menu[position]);
}
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
I see you're using the latest AppCompat and stuff. Then why complicate the drawer?
Please go through this. You can make a drawer VERY quickly and easily, handle its open and close quite neatly. You don't even need the ActionBarDrawerToggle.
Cheers.
Related
I want to add slider down menu in Navigation Drawer like this.
After click left side icon, it shows like this.
What can be done for this ?
This is Navigation Drawer with ExpandableListview
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private String[] items;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private NavigationManager mNavigationManager;
private Map<String, List<String>> mExpandableListData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mNavigationManager = FragmentNavigationManager.obtain(this);
initItems();
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
if (savedInstanceState == null) {
selectFirstItemAsDefault();
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void selectFirstItemAsDefault() {
if (mNavigationManager != null) {
String firstActionMovie = getResources().getStringArray(R.array.actionFilms)[0];
mNavigationManager.showFragmentAction(firstActionMovie);
getSupportActionBar().setTitle(firstActionMovie);
}
}
private void initItems() {
items = getResources().getStringArray(R.array.film_genre);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
if (items[0].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentAction(selectedItem);
} else if (items[1].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentComedy(selectedItem);
} else if (items[2].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentDrama(selectedItem);
} else if (items[3].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentMusical(selectedItem);
} else if (items[4].equals(mExpandableListTitle.get(groupPosition))) {
mNavigationManager.showFragmentThriller(selectedItem);
} else {
throw new IllegalArgumentException("Not supported fragment type");
}
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.film_genres);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
For more see this https://github.com/msahakyan/expandable-navigation-drawer
I want to implement drawer functionality in my android application just like flipkart can anyone help how to show subcategories in the same drawer on the click of respected category
Try to use Expandable listview in drawer like this
https://github.com/msahakyan/expandable-navigation-drawer
public class MainActivity extends ActionBarActivity {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
private ExpandableListView mExpandableListView;
private ExpandableListAdapter mExpandableListAdapter;
private List<String> mExpandableListTitle;
private Map<String, List<String>> mExpandableListData;
private TextView mSelectedItemView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
mExpandableListView = (ExpandableListView) findViewById(R.id.navList);
mSelectedItemView = (TextView) findViewById(R.id.selected_item);
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.nav_header, null, false);
mExpandableListView.addHeaderView(listHeaderView);
mExpandableListData = ExpandableListDataSource.getData(this);
mExpandableListTitle = new ArrayList(mExpandableListData.keySet());
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() {
mExpandableListAdapter = new CustomExpandableListAdapter(this, mExpandableListTitle, mExpandableListData);
mExpandableListView.setAdapter(mExpandableListAdapter);
mExpandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
getSupportActionBar().setTitle(mExpandableListTitle.get(groupPosition).toString());
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString());
}
});
mExpandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
getSupportActionBar().setTitle(R.string.film_genres);
mSelectedItemView.setText(R.string.selected_item);
}
});
mExpandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String selectedItem = ((List) (mExpandableListData.get(mExpandableListTitle.get(groupPosition))))
.get(childPosition).toString();
getSupportActionBar().setTitle(selectedItem);
mSelectedItemView.setText(mExpandableListTitle.get(groupPosition).toString() + " -> " + selectedItem);
mDrawerLayout.closeDrawer(GravityCompat.START);
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(R.string.film_genres);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#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);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I followed a tutorial to set a navigation drawer and it worked in my main activity. Now I tried to move it to almost every other activity creating a BaseActivity, but after making changes, navigation drawer icon is inactive, and does nothing when pressed.
MainActivity code:
public class MainActivity extends BaseActivity {
private WebView mWebView;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//Hide the semy cirle at th bottom of the action bar when the user slides to the top
mWebView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
//mainWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
view.stopLoading(); // may not be needed
switch (Locale.getDefault().toString()) {
case "es_ES":
view.loadUrl("file:///android_asset/www/errorPage.forMainActivity.es_ES.HTML");
break;
default:
view.loadUrl("file:///android_asset/www/errorPage.forMainActivity.en_US.HTML");
break;
}
}
#Override
public void onPageFinished(WebView view, String url) {
//sendRegistrationIdToBackend();
//getCookies();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("CommentsPopUp")) {
Intent a = new Intent(MainActivity.this, CommentsPopUpActivity.class);
startActivity(a);
} else if (url.contains("postPopUp")) {
Intent b = new Intent(MainActivity.this, PostPopUpActivity.class);
startActivity(b);
} else if (url.contains("ProfilePicPopUp")) {
Intent c = new Intent(MainActivity.this, ProfilePicPopUpActivity.class);
startActivity(c);
} else if (url.contains("PostPicPopUp")) {
Intent c = new Intent(MainActivity.this, PostPicsPopUpActivity.class);
startActivity(c);
} else if (url.contains("reloadIndex")) {
mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/");
} else if (Uri.parse(url).getHost().length() == 0) {
return false;
} else { // Otherwise, give the default behavior (open in browser)
mWebView.loadUrl(url);
}
return true;
}
});
mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/");
// Stop local links and redirects from opening in browser instead of WebView
// mWebView.setWebViewClient(new MyAppWebViewClient());
}
#Override
public void onBackPressed(){
super.onBackPressed();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
public void getCookies() {
CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie("http://192.168.0.6/");
//Log.i("UdazzT", cookies);
}
}
BaseActivity code:
public class BaseActivity extends AppCompatActivity {
ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
mNavItems.add(new NavItem(getResources().getString(R.string.myPosts), "", R.mipmap.ic_action_home));
mNavItems.add(new NavItem(getResources().getString(R.string.myFriends), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.findFriends), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.profileInfo), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.profilePic), "", R.mipmap.ic_action_about));
mNavItems.add(new NavItem(getResources().getString(R.string.notifications), "", R.mipmap.ic_action_settings));
mNavItems.add(new NavItem(getResources().getString(R.string.contact), "", R.mipmap.ic_action_settings));
mNavItems.add(new NavItem(getResources().getString(R.string.logOut), "", R.mipmap.ic_action_about));
// DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
// Populate the Navigtion Drawer with options
mDrawerPane = (RelativeLayout) findViewById(R.id.drawerPane);
mDrawerList = (ListView) findViewById(R.id.navList);
DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);
mDrawerList.setAdapter(adapter);
// Drawer Item click listeners
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItemFromDrawer(position);
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
}
#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_base, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle
// If it returns true, then it has handled
// the nav drawer indicator touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// 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);
}
#Override
public void onBackPressed(){
if(mDrawerLayout.isDrawerOpen(Gravity.LEFT)){ //replace this with actual function which returns if the drawer is open
mDrawerLayout.closeDrawer(Gravity.LEFT); // replace this with actual function which closes drawer
}
else{
super.onBackPressed();
}
}
/*
* Called when a particular item from the navigation drawer
* is selected.
* */
private void selectItemFromDrawer(int position) {
switch (position) {
case 0:
Intent a = new Intent(this, MyPostsActivity.class);
startActivity(a);
break;
case 1:
Intent b = new Intent(this, MyFriendsActivity.class);
startActivity(b);
break;
case 2:
Intent c = new Intent(this, FindFriendsActivity.class);
startActivity(c);
break;
case 3:
Intent d = new Intent(this, MyProfileInfoActivity.class);
startActivity(d);
break;
case 5:
Intent f = new Intent(this, MyNotificationsActivity.class);
startActivity(f);
break;
case 6:
Intent g = new Intent(this, ContactActivity.class);
startActivity(g);
break;
case 7:
//mWebView.loadUrl("http://192.168.0.6/udazz/2.0/2.1/android/2.0/signOut.php");
break;
}
mDrawerList.setItemChecked(position, true);
//setTitle(mNavItems.get(position).mTitle);
// Close the drawer
mDrawerLayout.closeDrawer(mDrawerPane);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
}
class NavItem {
String mTitle;
String mSubtitle;
int mIcon;
public NavItem(String title, String subtitle, int icon) {
mTitle = title;
mSubtitle = subtitle;
mIcon = icon;
}
}
class DrawerListAdapter extends BaseAdapter {
Context mContext;
ArrayList<NavItem> mNavItems;
public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
mContext = context;
mNavItems = navItems;
}
#Override
public int getCount() {
return mNavItems.size();
}
#Override
public Object getItem(int position) {
return mNavItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.drawer_item, null);
}
else {
view = convertView;
}
TextView titleView = (TextView) view.findViewById(R.id.title);
TextView subtitleView = (TextView) view.findViewById(R.id.subTitle);
ImageView iconView = (ImageView) view.findViewById(R.id.icon);
titleView.setText(mNavItems.get(position).mTitle);
subtitleView.setText(mNavItems.get(position).mSubtitle);
iconView.setImageResource(mNavItems.get(position).mIcon);
return view;
}
}
i have given this answer.
refer to this https://stackoverflow.com/a/30490289/3498931 and
in your case, implement syncState() method after the setting the listener to mDrawerLayout.
mDrawerLayout.setDrawerListener(drawerToggle);
after this statement, use the code i given in link. also you have duplication of code, remove the code from class which is not applicable. both way it is possible, but keep one only whichever works to avoid further conflict, unreadability or confustion.
I'm having lot of problems when implementing ActionBar Sherlock, the last one is this one. I have an Slide Menu whith 3 options in my ActionBar. My problem is that when I choose one item (it load a fragment) that has been previously selected the app crash. The log error is
The specified child already has a parent. You must call removeView()
on the child's parent first.
It mark a line where I add view to a HorizontalScroller.
lls.addView(mviews.get(i));
In my OnCreateView I have
final View v = inflater.inflate(R.layout.activity_landing, container,false);
container.removeAllViews();
I haved tried many different ways posted here, but I don't get thw solution to my problem. Any ideas?
EDIT:
Here is some code of my MainActivity and Fragment.
This is the MainActivity. Ther's a ScreenSplash after and a class that extends from Application that control all WebService communications.
public class MainActivity extends SherlockFragmentActivity {
//Declare Variables
//...
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
Fragment fragment3 = new Fragment3();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
getSupportActionBar().setTitle("");
setContentView(R.layout.drawer_main);
// Generate title
title = new String[] { "Item 1", "Item 2", "Item 3", "Item 4" };
// Generate icon
icon = new int[] { R.drawable.item1, R.drawable.item2,
R.drawable.item3, R.drawable.item4};
// Locate DrawerLayout in drawer_main.xml
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// Locate ListView in drawer_main.xml
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);
// Pass results to MenuListAdapter Class
mMenuAdapter = new MenuListAdapter(this, title, subtitle, icon);
// Set the MenuListAdapter to the ListView
mDrawerList.setAdapter(mMenuAdapter);
// Capture button clicks on side menu
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
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
//FOR ABS y ND
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_main, menu);
//Define ActionBar buttons and actions
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//Sliding lateral Menu
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
// The click listener 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) {
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, fragment3);
break;
}
ft.commit();
mDrawerList.setItemChecked(position, true);
// Close drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
#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 toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
This is the fragment with error. Now the other two are empty.
public class Fragment1 extends SherlockFragment implements
AdapterView.OnItemClickListener {
//DeclareVariables
public Fragment1() {
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//some declaration ad settings (witdhs, typefaces, caches,...)
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.main_activity, null,
false);
container.removeAllViews();
lls = (LinearLayout) v.findViewById(R.id.lscroll_item);
lls.removeAllViews();
//Instantiate some elements of the view such as TextViews and ImageViews
//layoutParams
// Show Scroll
DataStore.sharedInstance().getInfo(
new DataStore.infoReturn() {
#Override
public void call(final ArrayList<User> users, int error) {
if(users != null){
for (i = 0; i < users.size(); i++) {
mviews.add((RelativeLayout) getActivity().getLayoutInflater().inflate(R.layout.item_user, null));
mviews.get(i).setLayoutParams(layoutParams2);
imv = (ImageView) mviews.get(i).findViewById(R.id.user);
imv.getLayoutParams().height=friend_height;
imv_click = (ImageView) mviews.get(i).findViewById(R.id.click);
TextView text2 = (TextView) mviews.get(i).findViewById(R.id.fav);
text2.setTypeface(myTypeFace);
//set widths and layoutParams and sources
mviews.get(i).setId(i);
//NEXT LINE IS THE CRASH POINT, WHERE I TRY TO ADD ITEMS TO THE VIEW
lls.addView(mviews.get(i));
mviews.get(i).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
//Set actins when click
}
});
}
}else{
switch (error) {
case -1: //ERROR OBTENER USERS
break;
default:
break;
}
}
}
});
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// actions when click
}
#Override
public void onResume() {
super.onResume();
refreshInfo();
refreshSelectedUsers();
}
#Override
public void onPause() {
super.onPause();
DataStore.sharedInstance().setSelectedUsers(mSelected);
}
#Override
public void onDestroy() {
super.onDestroy();
//delete cache
}
//Some other methods for other UI items.
}
I have hidden some code to make it easier to read.
Use this
final View v = inflater.inflate(R.layout.activity_landing, null, false);
instead of
final View v = inflater.inflate(R.layout.activity_landing, container,false);
I am currently trying to implement the new NavigationDrawer as per the Google IO 2013 guidelines. I am using ActionbarSherlock. The code is working well. The only issue is that I am not able to toggle the "up" caret next to my app icon when the navigation drawer is pulled out. I am pasting my entire code below. Kindly help.
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
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) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
new Thread(new Runnable() {
#Override
public void run() {
prefs = getPreferences(MODE_PRIVATE);
opened = prefs.getBoolean(OPENED_KEY, false);
if(opened == false)
{
mDrawerLayout.openDrawer(mDrawerList);
}
}
}).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(getMenuItem(item))) {
return true;
}
switch (item.getItemId()) {
case R.id.action_websearch:
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getSupportActionBar().getTitle());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private android.view.MenuItem getMenuItem(final MenuItem item) {
return new android.view.MenuItem() {
#Override
public int getItemId() {
return item.getItemId();
}
public boolean isEnabled() {
return true;
}
#Override
public boolean collapseActionView() {
return false;
}
#Override
public boolean expandActionView() {
return false;
}
#Override
public ActionProvider getActionProvider() {
return null;
}
#Override
public View getActionView() {
return null;
}
#Override
public char getAlphabeticShortcut() {
return 0;
}
#Override
public int getGroupId() {
return 0;
}
#Override
public Drawable getIcon() {
return null;
}
#Override
public Intent getIntent() {
return null;
}
#Override
public ContextMenuInfo getMenuInfo() {
return null;
}
#Override
public char getNumericShortcut() {
return 0;
}
#Override
public int getOrder() {
return 0;
}
#Override
public SubMenu getSubMenu() {
return null;
}
#Override
public CharSequence getTitle() {
return null;
}
#Override
public CharSequence getTitleCondensed() {
return null;
}
#Override
public boolean hasSubMenu() {
return false;
}
#Override
public boolean isActionViewExpanded() {
return false;
}
#Override
public boolean isCheckable() {
return false;
}
#Override
public boolean isChecked() {
return false;
}
#Override
public boolean isVisible() {
return false;
}
#Override
public android.view.MenuItem setActionProvider(ActionProvider actionProvider) {
return null;
}
#Override
public android.view.MenuItem setActionView(View view) {
return null;
}
#Override
public android.view.MenuItem setActionView(int resId) {
return null;
}
#Override
public android.view.MenuItem setAlphabeticShortcut(char alphaChar) {
return null;
}
#Override
public android.view.MenuItem setCheckable(boolean checkable) {
return null;
}
#Override
public android.view.MenuItem setChecked(boolean checked) {
return null;
}
#Override
public android.view.MenuItem setEnabled(boolean enabled) {
return null;
}
#Override
public android.view.MenuItem setIcon(Drawable icon) {
return null;
}
#Override
public android.view.MenuItem setIcon(int iconRes) {
return null;
}
#Override
public android.view.MenuItem setIntent(Intent intent) {
return null;
}
#Override
public android.view.MenuItem setNumericShortcut(char numericChar) {
return null;
}
#Override
public android.view.MenuItem setOnActionExpandListener(OnActionExpandListener listener) {
return null;
}
#Override
public android.view.MenuItem setOnMenuItemClickListener(OnMenuItemClickListener menuItemClickListener) {
return null;
}
#Override
public android.view.MenuItem setShortcut(char numericChar, char alphaChar) {
return null;
}
#Override
public void setShowAsAction(int actionEnum) {
}
#Override
public android.view.MenuItem setShowAsActionFlags(int actionEnum) {
return null;
}
#Override
public android.view.MenuItem setTitle(CharSequence title) {
return null;
}
#Override
public android.view.MenuItem setTitle(int title) {
return null;
}
#Override
public android.view.MenuItem setTitleCondensed(CharSequence title) {
return null;
}
#Override
public android.view.MenuItem setVisible(boolean visible) {
return null;
}
};
}
/* 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) {
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#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);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends SherlockFragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
// change int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()), "drawable", getActivity().getPackageName());
int imageId = getResources().getIdentifier("tempmap", "drawable", getActivity().getPackageName());
// change ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
// change getActivity().setTitle(planet);
getActivity().setTitle("MapView");
return rootView;
}
}
}
If you don't need the 3 lines to move (like in gmail app), you could just add:
<item name="homeAsUpIndicator">#drawable/ic_drawer</item>
<item name="android:homeAsUpIndicator">#drawable/ic_drawer</item>
in your activity's theme. I prefer this to using yet another library in my app.
ic_drawer can be downloaded from here:
http://developer.android.com/training/implementing-navigation/nav-drawer.html
try to call syncState on the toggle drawer like this:
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
//your ActionBarDrawerToggle is below
mDrawerToggle.syncState();
}
or just right after you instantiate it.
I had the same problem and did some research on that topic. It does not seem to be easy to get the caret working correctly on older SDKs. Long story short, there's a guy who has a running example implementation that's based on reflection:
https://github.com/nicolasjafelle/SherlockNavigationDrawer
I tested it and it works perfectly for me, even on Android 2.x !
I have the caret removed in 4.x devices, but not for 2.x devices. The repository is here if you need it:
https://github.com/bcrider/NavigationDrawerSherlocked
It's simply the sample that Google supplied that I modified using ActionBarSherlock as you have done as well. I fixed an issue with a method (onOptionsItemSelected) in the sample that originally prevented the tapped icon from doing anything after ActionBarSherlock was integrated into the app.
Hope this helps!