I am trying to understand how to implement the ActionBarSherlock Navigation Drawer into a project. I have one working with the official Android implementation but I would like it to run at 2.2+ so I am looking into ActionBarSherlock. I have an error under the selectItem(int position) section of the code. I will paste it here:
package com.rufflez.absnavdrawer;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends SherlockFragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mFragmentTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mFragmentTitles = getResources().getStringArray(R.array.fragments);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer);
mDrawerList = (ListView)findViewById(R.id.drawer_list);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mFragmentTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
public void onDrawerClosed(View v){
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View v){
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null){
selectItem(0);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu){
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case android.R.id.home:
if (mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, Sources.class);
startActivity(i);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener{
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id){
selectItem(position);
}
}
private void selectItem(int position){
Fragment newFragment = new Fragment_1();
FragmentManager fm = getSupportFragmentManager();
switch(position){
case 0:
newFragment = new Fragment_1();
break;
case 1:
newFragment = new Fragment_2();
break;
case 2:
newFragment = new Fragment_3();
break;
case 3:
newFragment = new Fragment_4();
break;
case 4:
newFragment = new Fragment_5();
break;
}
fm.beginTransaction()
.replace(R.id.content_frame, newFragment)
.commit();
mDrawerList.setItemChecked(position, true);
setTitle(mFragmentTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title){
mTitle = title;
getSupportActionBar().setTitle(title);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
As I said above, the error is under selectItem and specifically error under new Fragment_1(); and again at new Fragment_1();. The eclipse message is Type mismatch: cannot convert from Fragment_1 to Fragment.
This is Fragment_1.java:
package com.rufflez.absnavdrawer;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class Fragment_1 extends FragmentActivity{
WebView webview;
private String url;
ProgressBar pd = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// pd = (ProgressBar) findViewById(R.id.web_view_progress_bar);
// webview = (WebView) findViewById(R.id.WebView);
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(progress < 100 && pd.getVisibility() == View.GONE){
pd.setVisibility(View.VISIBLE);
}
pd.setProgress(progress);
if(progress == 100) {
pd.setVisibility(View.GONE);
}
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
// then it is not handled by default action
}
});
webview.loadUrl("file:///android_asset/about.html");
}
#Override
public void onBackPressed()
{
if(webview.canGoBack())
webview.goBack();
else
super.onBackPressed();
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
I think you are missing a cast, since new Fragment_1() will return class Fragment_1, and not Fragment.
Oh! Fragment_1() is FragmentActivity Which is an Activity different from Fragment!
see it
Dilemma: when to use Fragments vs Activities:
Your fragment isn't a fragment.
Change onCreate to onCreateView and do this code;
public class Fragment_1 extends SherlockFragment{
i think that is the error.
if not, try rebuilding your fragment in this one
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;
public class Fragment_1 extends SherlockFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.frag1, container, false);
//change frag1 to corresponding XML
}
}
Related
In my android app i have created 4 tabs with the fragment and each tab loads different URL, which works fine but,
1) how do i add onBackpressed to each webview to load previous page on back click? I know how to do it in java class but Override doesn't work in Fragment.
2) my second question is I have added a ProgressDialog to each webview which works fine but covers whole layout until full webpage is loaded, how do i make it show only on top like browsers, while able to view and scroll loaded webpage?
Following is my code for fragment.
GoogleFragment.java
Public class GoogleFragment extends Fragment {
WebView myWebView;
ProgressDialog pd;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_webview, container, false);
final ProgressDialog pd = ProgressDialog.show(getContext(), "", "Loading Please wait...", true);
myWebView = (WebView) v.findViewById(R.id.WebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.google.com/");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
//improve webView performance
myWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
myWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
myWebView.getSettings().setAppCacheEnabled(true);
myWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
String webUrl = myWebView.getUrl();
}
});
return v;
}
}
MainActivity.java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.nav.R;
import com.nav.fragments.TabFragment;
import java.util.Timer;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
private InterstitialAd interstitial;
public Timer AdTimer;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer) ;
int width = getResources().getDisplayMetrics().widthPixels/2;
DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mNavigationView.getLayoutParams();
params.width = width;
mNavigationView.setLayoutParams(params);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
//setTitle(menuItem.getTitle());
if (menuItem.getItemId() == R.id.drawer_home) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new TabFragment()).commit();
}
if (menuItem.getItemId() == R.id.drawer_facebook){
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_gPlus){
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_rate) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_more) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_profile) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_share) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_youtube) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
if (menuItem.getItemId() == R.id.drawer_exit) {
Toast.makeText(MainActivity.this,
"Replace with your own function", Toast.LENGTH_LONG).show();
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
} }
TabFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.nav.R;
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 6 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_layout, container, false);
tabLayout = (TabLayout) v.findViewById(R.id.tabs);
viewPager = (ViewPager) v.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return v;
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new GoogleFragment();
case 1 : return new SportsFragment();
case 2 : return new GamesFragment();
case 3 : return new PhotographyFragment();
case 4 : return new WildFragment();
case 5 : return new TravelFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return getResources().getString(R.string.tab1);
case 1 :
return getResources().getString(R.string.tab2);
case 2 :
return getResources().getString(R.string.tab3);
case 3 :
return getResources().getString(R.string.tab4);
case 4 :
return getResources().getString(R.string.tab5);
case 5 :
return getResources().getString(R.string.tab6);
}
return null;
}
}
}
You can change onBackPressed in the activity:
http://pastebin.com/3DR4nDWM
And in your fragment class:
public boolean goBack()
{
if(webView.canGoBack())
{
webView.goBack();
return true;
}
return false;
}
Try adding ProgressBar on top of the WebView.
I would like that the title in the menu will change by the fragment name that was click. for the code below what i get is that, the actual title in each fragment is "Home" and its does not change. but i found that when i click on an item in the menu the title changing for a second and return back to the "Home" title. i implemented the ondrawer but still i don't know what could cause that.
my code:
package com.example.matant.gpsportclient;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.matant.gpsportclient.Controllers.Fragments.CreateEventFragmentController;
import com.example.matant.gpsportclient.Controllers.DBcontroller;
import com.example.matant.gpsportclient.Controllers.Fragments.GoogleMapFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ManageEventFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ProfileFragmentController;
import com.example.matant.gpsportclient.InterfacesAndConstants.AsyncResponse;
import com.example.matant.gpsportclient.InterfacesAndConstants.Constants;
import com.example.matant.gpsportclient.Utilities.DrawerItem;
import com.example.matant.gpsportclient.Utilities.DrawerItemCustomAdapter;
import com.example.matant.gpsportclient.Utilities.SessionManager;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainScreen extends AppCompatActivity implements AsyncResponse {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DBcontroller dbController;
private ProgressDialog progress = null;
private SessionManager sm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
if (getIntent().getBooleanExtra("EXIT", false)) {
finish();
return;
}
mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
sm = SessionManager.getInstance(this);
mTitle = mDrawerTitle = "Home";
DrawerItem [] drawerItems = new DrawerItem[Constants.MENU_SIZE];
drawerItems[0] = new DrawerItem(R.drawable.home,"Home");
drawerItems[1] = new DrawerItem(R.drawable.profile,"Profile");
drawerItems[2] = new DrawerItem(R.drawable.search,"Search Events");
drawerItems[3] = new DrawerItem(R.drawable.create,"Create Event");
drawerItems[4] = new DrawerItem(R.drawable.manage,"Manage Event");
drawerItems[5] = new DrawerItem(R.drawable.attending,"Attending List");
drawerItems[6] = new DrawerItem(R.drawable.recent_search_24,"Recent Searches");
drawerItems[7] = new DrawerItem(R.drawable.logout,"Log Out");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[0]);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void handleResponse(String resStr) {
try
{
if((this.progress!= null )&& this.progress.isShowing())
{
this.progress.dismiss();
}
}catch (final IllegalArgumentException e){
Log.d("Dialog error",e.getMessage());
}catch (final Exception e){
Log.d("Dialog error",e.getMessage());
}
finally {
this.progress = null;
}
Log.d("handleResponse", resStr);
if(resStr!=null)
{
try {
JSONObject jsonObj = new JSONObject(resStr);
String flg = jsonObj.getString(Constants.TAG_FLG);
switch (flg) {
case "user logged out":
{
sm.logoutUser();
break;
}
case "query failed": {
Toast.makeText(getApplicationContext(),"Error Connection",Toast.LENGTH_LONG).show();
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void sendDataToDBController() {
String user = sm.getUserDetails().get(Constants.TAG_EMAIL);
BasicNameValuePair tagReq = new BasicNameValuePair("tag","logout");
BasicNameValuePair userNameParam = new BasicNameValuePair("username",user);
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(tagReq);
nameValuePairList.add(userNameParam);
dbController = new DBcontroller(this,this);
dbController.execute(nameValuePairList);
}
#Override
public void preProcess() {
this.progress = ProgressDialog.show(this, "Log Out",
"Logging out...", true,false);
}
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) {
Fragment fragment = null;
switch (position) {
case 0: //Home
fragment = new GoogleMapFragmentController();
break;
case 1: //Profile
fragment = new ProfileFragmentController();
break;
case 2: //Search Events
//fragment = new SearchEventFragmentController();
break;
case 3: //Create Events
fragment = new CreateEventFragmentController();
break;
case 4: //Manage Events
fragment = new ManageEventFragmentController();
break;
case 5: //Attending List
//fragment = new AttendingListFragmentController();
break;
case 6: //Recent Searches
//fragment = new RecentSearchesFragmentController();
break;
case 7: { //Log Out
logout();
finish(); //destroy the main activity
}
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
getSupportActionBar().setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void logout()
{
sendDataToDBController();
}
/*#Override
protected void onDestroy() {
super.onDestroy();
logout();
}*/
}
Set it for all your fragment. This should do the work!!
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.id.your_fragment_layout, container,
false);
getActivity().setTitle("<your title>");
return rootView;
}
try this:
#Override
public void onResume() {
super.onResume();
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("Your Title");
}
Ok i found the problem, your answer was good and i really change the title each time from the fragment but in addition i need to disable this line:
getSupportActionBar().setTitle(mDrawerTitle);
from the onDrawerOpened and onDrawerClosed
Do not set the title to ActionBar, set the title to Activity, you can do so from the activity or fragment.
For Activity:
setTitle("New Title");
or for Fragment:
getActivity().setTitle("New Title");
add this in your fragment
getActivity().setTitle("title");
add remove this below line from Drawer activity
getActivity().setTitle("title");
Try this one it worked for me
place a Textview inside the toolbar of app_bar activity
Inside the oncreateView of a fragment put this code
TextView heading;
heading=(TextView)getActivity().findViewById(R.id.Id_title);
heading.setText("your text");
By using this you can Name each fragments with your own text
In onCreateView()write following code:
activity!!.setTitle("Your Text")
If your purpose is "Changing toolbar title according to the fragment name"
i tip to see if the "navigation graph" of the "navigation drawer" you set all stuff correctly: every fragment should have something like this:
<fragment
android:id="#+id/nav_ID_OF_FRAGMENT"
android:name="rubik_cube.navigation.ui.NAME_OF_Fragment"
android:label="#string/TOOLBAR_TITLE_HERE"
tools:layout="#layout/fragment_LAYOUT_GO_HERE" />
and in the resources the fragment desired title string,
in the res/layout the layout of the fragment,
in the code a class that handle the fragment stuff
and toolbar works perfectly!
if u want to change toolbar name dinamically according to other stuff like idk pressing a button, select from menu u need to change it programmatically instead with:
ActionBar toolbar = requireActivity().getSupportActionBar();
if(toolbar != null) toolbar.setTitle("your title");
I currently have a menu that I load into my Toolbar which looks like this:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView"
android:onClick="goToSearch"
android:title="Search"/>
<item android:id="#+id/action_barcode"
android:icon="#drawable/bar"
android:title="barcode"
app:showAsAction="ifRoom"
android:onClick="scanBarcode"/>
</menu>
When you click the barcode icon, it loads my barcode scanning fragment. I want to clean up my toolBar and not have multiple icons up there. Essentially I want my search icon, that opens up when clicked to have two functions.
When clicked open the search bar.
When long pressed, open my barcode scan fragment.
Currently Number one works, looking at how to employ number 2.
This is what my code looks liek for launching the barcode scan fragment and search.
import android.IntentIntegrator;
import android.IntentResult;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Created by Mike and Simon on 2/22/14.
*/
public class MainDrawer2 extends ActionBarActivity
{
private static final String EXTRA_NAV_ITEM = "extraNavItem";
private static final String STATE_CURRENT_NAV = "stateCurrentNav";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private NavDrawerListAdapter mDrawerAdapter;
private ListView mDrawerList;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private MainNavItem mCurrentNavItem;
public static Intent createLaunchFragmentIntent(Context context, MainNavItem navItem)
{
return new Intent(context, MainDrawer2.class)
.putExtra(EXTRA_NAV_ITEM, navItem.ordinal());
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//Crashlytics.start(this);
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList = (ListView)findViewById(R.id.drawer);
// Set a toolbar to replace the action bar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getActionBar().setDisplayHomeAsUpEnabled(true);
//enableHomeButtonIfRequired();
mDrawerAdapter = new NavDrawerListAdapter(getApplicationContext());
mDrawerList.setAdapter(mDrawerAdapter);
mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
displayNavFragment((MainNavItem)parent.getItemAtPosition(position));
}
});
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_menu_white, R.string.app_name, R.string.app_name)
{
public void onDrawerClosed(View view)
{
//getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
//getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if(getIntent().hasExtra(EXTRA_NAV_ITEM)){
MainNavItem navItem = MainNavItem.values()
[getIntent().getIntExtra(EXTRA_NAV_ITEM,
MainNavItem.STATISTICS.ordinal())];
displayNavFragment(navItem);
}
else if(savedInstanceState != null){
mCurrentNavItem = MainNavItem.values()
[savedInstanceState.getInt(STATE_CURRENT_NAV)];
setCurrentNavItem(mCurrentNavItem);
}
else{
displayNavFragment(MainNavItem.STATISTICS);
}
}
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
private void enableHomeButtonIfRequired()
{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
//getActionBar().setHomeButtonEnabled(true);
}
}
public void setActionBarTitle(String title) {
//getActionBar().setTitle(title);
}
#Override
public void setTitle(CharSequence title)
{
mTitle = title;
//getActionBar().setTitle(mTitle);
}
#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);
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
if (mCurrentNavItem == null){
}
else{
outState.putInt(STATE_CURRENT_NAV, mCurrentNavItem.ordinal());
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/*
#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);
}
*/
private void displayNavFragment(MainNavItem navItem)
{
//if(navItem == mCurrentNavItem){
// return;
//}
Fragment fragment = Fragment.instantiate(this,
navItem.getFragClass().getName());
if(fragment != null){
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, fragment)
.commit();
//setCurrentNavItem(navItem);
}
}
private void setCurrentNavItem(MainNavItem navItem)
{
int position = navItem.ordinal();
// If navItem is in DrawerAdapter
if(position >= 0 && position < mDrawerAdapter.getCount()){
//mDrawerList.setItemChecked(position, true);
}
else{
// navItem not in DrawerAdapter, de-select current item
if(mCurrentNavItem != null){
//mDrawerList.setItemChecked(mCurrentNavItem.ordinal(), false);
}
}
//test to keep item not selected
int toClear=mDrawerList.getCheckedItemPosition();
if (toClear >= 0) {
mDrawerList.setItemChecked(toClear, false);
}
mDrawerLayout.closeDrawer(mDrawerList);
//setTitle(navItem.getTitleResId());
mCurrentNavItem = navItem;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if(mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
}
else {
mDrawerLayout.openDrawer(mDrawerList);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void goToSearch(MenuItem item){
//go to search page
Fragment Fragment_one;
FragmentManager man= getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new Search();
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
public void scanBarcode(MenuItem item){
//open scanner
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanContent = scanningResult.getContents();
//todo: set scan content into setting, load new fragment which calls async task below. New
//todo: fragment will have same ui as search. :-)
Fragment Fragment_one;
FragmentManager man= this.getSupportFragmentManager();
FragmentTransaction tran = man.beginTransaction();
BarcodeFrag fragmentNew = new BarcodeFrag();
Bundle bundle = new Bundle();
bundle.putString("scanContent", scanContent);
fragmentNew.setArguments(bundle);
tran.replace(R.id.main, fragmentNew);//tran.
tran.addToBackStack(null);
//tran.commit();
tran.commitAllowingStateLoss();
}
else{
Toast toast = Toast.makeText(getApplicationContext(),
"No scan data received!", Toast.LENGTH_SHORT);
toast.show();
}
}
}
The action bar concept doesn't count on this requirement, so using built-in functionality you'll never be able to achieve what you need.
You can, however, introduce your own custom layout in stock action bar and do whatever you want there. See an example here:
http://javatechig.com/android/actionbar-with-custom-view-example-in-android
Hello i have a small problem with my project. I have a sliding menu with webviews . But i can't go back in webviews, when i push the button to go back my app just crash. I tryed with OnBackPressed method and OnKeyDown, but no one of this work. here is my code. just the main activity class and webviewfragment class
Where shoul i put the methods to work fine ? In webview fragment class, not work because webviews extend fragment, no fragmentActivity.
package com.pavan.slidingmenu;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
WebView webview ;
String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// 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, R.string.app_name,
R.string.app_name) {
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
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
String url = rowItems.get(position).getPageUrl();
Fragment fragment = new MyWebViewFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#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);
}
/**
* 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);
}
// #Override
// public void onBackPressed()
// {
// if(webview.canGoBack())
// webview.goBack();
// else
// super.onBackPressed();
// }
// #Override
// public boolean onKeyDown(int keyCode, KeyEvent event) {
// if(event.getAction() == KeyEvent.ACTION_DOWN){
// switch(keyCode)
// {
// case KeyEvent.KEYCODE_BACK:
// if(webview.canGoBack()){
// webview.goBack();
// }else{
// finish();
// }
// return true;
// }
//
// }
// return super.onKeyDown(keyCode, event);
// }
}
package com.pavan.slidingmenu;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewFragment extends Fragment {
ProgressDialog mProgress;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container,
false);
Bundle bundle = getArguments();
String url = bundle.getString("url");
webview = (WebView) rootView.findViewById(R.id.webview1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setBuiltInZoomControls(true);
settings.setPluginState(PluginState.ON);
mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
return rootView;
}
}
You just need to make your WebViewFragment implement an Interface, like this:
public interface onBackPressedInterface
{
public void onBackPressedWebView();
}
The only method of the Interface will be implemented on your fragment, so you have to add implements clause on your Fragment declaration, like this:
public class MyWebViewFragment extends Fragment implements onBackPressedInterface{
and implement the method like this:
/**
* the user presses the back button
*/
#Override
public void onBackPressedWebView()
{
if (webview.canGoBack()){
webview.goBack();
((MainActivity) getActivity()).canGoBack=true;
}
else{
((MainActivity) getActivity()).canGoBack=false;
getActivity().onBackPressed();
}
}
In your MainActivity, add a boolean variable that defines if you make the normal back behaviour or execute the Interface method on your Fragment. It is public so the Fragment can access it and modify it when there is no more backs to make on the WebView. It is true at the begginig so the interface method could be allways called at the first time the user clicks back button.
public boolean canGoBack = true;
Once the user clicks the back button, the onBackPressed() callback is called on your MainActivity, so overrite it like this:
#Override
public void onBackPressed()
{
if(canGoBack)
((onBackPressedInterface)getSupportFragmentManager().findFragmentById(R.id.webview_fragment)).onBackPressedWebView();
if(!canGoBack)
super.onBackPressed();
}
R.id.webview_fragment is the id of the fragment that I have declared in my Activity layout file.
So, when the user clicks back button, the fragment method is called, it checks if the webview can go back. If it can, goes back and keeps the Activity boolean true so it can be executed again when a new click occurs.
When the WebView has no more backs, the variable is set to false and the normal onBackPressed method is executed, by calling getActivity().onBackPressed().
This is what your Activity layout should be like, with one fixed Fragment component:
<?xml version="1.0" encoding="utf-8"?>
<fragment
android:id="#+id/webview_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.pavan.slidingmenu.MyWebViewFragment" />
If you do not want to have a fixed Fragment in your layout, just create a call in your MyWebViewFragment to create an instance of your fragment, like:
MyWebViewFragment.newInstance() and call the interface callback on that Fragment
I started writing an app for Android. I have a problem with the Animation of the NavigationDrawer icon at the top left. It works correctly when the application is launched for the first time but when I pick an item from the list in the NavgationDrawer its icon stays in the "open" state even though the `NavigationDrawer closes as it should.
Here is my MainActivity:
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.app.ActionBar;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.content.res.*;
public class MainActivity extends FragmentActivity {
ActionBarDrawerToggle icon;
final String[] listContent ={"Accueil","Fiche technique","Pilotes","Ecuries"};
final String[] fragments ={
"com.mycompany.f1holo.MainPageFragment",
"com.mycompany.f1holo.FirstFragment",
"com.mycompany.f1holo.SecondFragment",
"com.mycompany.f1holo.ThirdFragment"};
private ActionBarDrawerToggle actionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> ad = new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, listContent);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView list = (ListView) findViewById(R.id.drawer);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this,
drawer,
R.drawable.navdrawer,
R.string.open,
R.string.close);
drawer.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
list.setAdapter(ad);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
transition.replace(R.id.mains, Fragment.instantiate(MainActivity.this, fragments[position]));
transition.commit();
}
});
drawer.closeDrawer(list);
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId())
{
case R.id.mainMenuAbout:
Toast.makeText(this, "F1 Holo", Toast.LENGTH_SHORT).show();
return true;
case R.id.mainMenuQuitter:
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
getMenuInflater().inflate(R.menu.main_about, menu);
return true;
}
}
And here is my FirstFragment:
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FirstFragment extends Fragment {
public static Fragment newInstance(Context context) {
FirstFragment frag = new FirstFragment();
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.first_fragment_layout, null);
return root;
}
}
I have found the solution and it is so obvious I could kick myself for not noticing before...
The problem is here:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
transition.replace(R.id.mains, Fragment.instantiate(MainActivity.this, fragments[position]));
transition.commit();
}
});
drawer.closeDrawer(list);
}
});
In this OnClickListener you are setting a new SimpleDrawerListener and therefore overriding this line:
drawer.setDrawerListener(actionBarDrawerToggle);
This disconnects the ActionBarDrawerToogle from the DrawerLayout and as a result stops the animations from playing... This is all you need:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
transition.replace(R.id.mains, Fragment.instantiate(MainActivity.this, fragments[position]));
transition.commit();
drawer.closeDrawer(list);
}
});
Why would you want to do this anyway? It just causes a delay between the user picking the item and the content actually changing. If it is because of performance issues - maybe that the close animation of the NavigationDrawer is not playing correctly - then doing something like this might be appropriate but in any case if you decide to implement this do it like this:
First create global variable called drawerItemSelection:
private String drawerItemSelection = null;
And then implement your ItemClickListener like this:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parent, View view, final int position, long id) {
drawerItemSelection = fragments[position];
drawer.closeDrawer(list);
}
});
And finally in your onCreate() method implement the ActionBarDrawerToogle like this:
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawer, R.drawable.navdrawer, R.string.open, R.string.close) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if(drawerItemSelection != null) {
FragmentTransaction transition = getSupportFragmentManager().beginTransaction();
transition.replace(R.id.mains, Fragment.instantiate(MainActivity.this, drawerItemSelection));
transition.commit();
drawerItemSelection = null;
}
}
};
If you have any further questions feel free to ask!