I am trying to create an app. I am not getting name on Action bar. when go back to main activity from a fragment that moment we going back to main activity but name on action bar is not change showing Name of fragment after go to back on main activity Using the following code-
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener{
DrawerLayout mDrawerLayout;
ListView mDrawerList;
#SuppressWarnings("deprecation")
ActionBarDrawerToggle mDrawerToggle;
String mTitle="";
private final String TAG = this.getClass().getSimpleName();
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,NearbyPlace,FindMarker;
EditText editplace = null;
Button findbtn = null;
boolean firstRun = true;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for connectivity service
ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cManager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnected()) {
Toast.makeText(this, "Network is available ", Toast.LENGTH_SHORT).show();
AdView adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice("abc")
.build();
adView.loadAd(adRequest);
mFragment=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
else{
Toast.makeText(this, "Network is not available ", Toast.LENGTH_SHORT).show();
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
newFragment = new NetworkCheck();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
editplace = (EditText) findViewById(R.id.editplace);
findbtn = (Button) findViewById(R.id.findbtn);
setListnerOnWidget();
mTitle = (String) getTitle();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle( this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Select a menu");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.menu)
);
mDrawerList.setAdapter(adapter);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
displayView(position);
// Updating the action bar title
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new Help();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
newFragment = new ContactUs();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
transaction.addToBackStack(null);
try
{ Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "Choose an action"));
}
catch(Exception e)
{ //e.toString();
}
Log.e(TAG, "share button is clicked");
break;
case 3:
newFragment = new Suggestion_Address();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "Suggestion Address button is clicked");
break;
}
}
});
}
private void setListnerOnWidget() {
// TODO Auto-generated method stub
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = editplace.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}
}
};
findbtn.setOnClickListener(listener);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
//for back button
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 1) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
Please tell me how show name on action bar of main activity when go back to main activity from a fragment.
Thanks
you can have a method in main activity which setting action bar , which you can call in Onresume of Main Activity .
example Main Activity Method :
public void setActionBar(CharSequence title) {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Use this line of code in your fragment where from you back to MainActivity
#Override
public void onDestroyView() {
super.onDestroyView();
(AppCompatActivity) getActivity()).getSupportActionBar().setTitle("You Main Activity Title");
}
or try this
#Override
public void onDestroyView() {
super.onDestroyView();
getActivity().getSupportActionBar().setTitle("You Main Activity Title");
}
Related
I have a navigation drawer with fragments. At start, I display Home fragment as default.
There are options on navigation menu. In 2 fragments I have SwipeRefreshLayout. Until all recyclerview data are fetched then I display data and invisible SwipeRefreshLayout.
One of these fragments (included SwipeRefReshLayout) works fine but, in Home fragment something is wrong.
For example(use case)
You started app and you saw Home fragment
You clicked Profile fragment on navigation menu
You run onBackPressed(back button).
In this case data never loads and SwipeRefReshLayout is always spinning. (I also tried without refreshlayout, still same)
Any idea how to fix this? My thought is, its about displaying default fragment.
Navigation Drawer Activity
public class Page_Navigation extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment fragment;
FragmentManager fragmentManager = getSupportFragmentManager();
NavigationView navigationView;
SharedPreferences mSharedPref;
DrawerLayout drawer;
private Tracker mTracker;
FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page__navigation);
//
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView toolbar_head = findViewById(R.id.toolbar_head);
ImageView toolbar_image = findViewById(R.id.toolbar_image);
ImageView toolbar_profile = findViewById(R.id.toolbar_profile);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
//
AnalyticsApplication application = (AnalyticsApplication) getApplication();
mTracker = application.getDefaultTracker();
mTracker.setScreenName("page_navigation");
mTracker.send(new HitBuilders.ScreenViewBuilder().build());
//FIRST SETTINGS
setSupportActionBar(toolbar);
Typeface customFont = Typeface.createFromAsset(getAssets(), "Montserrat-Medium.ttf");
toolbar_head.setTypeface(customFont);
//Get Sessions
mSharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String session_user_name = mSharedPref.getString("session_user_name", "");
String session_user_photo = mSharedPref.getString("session_user_photo", "");
//Navigation Drawer
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setItemIconTintList(null);
//
View headerView = navigationView.getHeaderView(0);
TextView nav_userName = (TextView) headerView.findViewById(R.id.textView_nav_userName);
CircleImageView imageView_navigation = (CircleImageView) headerView.findViewById(R.id.imageView_navigation);
Glide.with(getApplicationContext()).load(session_user_photo).into(imageView_navigation);
nav_userName.setText(session_user_name);
headerView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.START)) {
drawer.closeDrawer(Gravity.START);
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showProfileFragment();
}
}, 300);
}
});
toolbar_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawer.openDrawer(GravityCompat.START);
}
});
toolbar_profile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment fragment;
FragmentManager manager = getSupportFragmentManager();
fragment = new Nav_Profile();
fragmentTransaction = manager.beginTransaction();
fragmentTransaction.replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
});
displayDefaultFragment();
}
#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 boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.page__navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
final int id = item.getItemId();
drawer.closeDrawer(GravityCompat.START);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
switch (id) {
case R.id.nav_home:
fragment = new Nav_Home();
break;
case R.id.nav_contact:
fragment = new Nav_Contact();
break;
case R.id.nav_articles:
fragment = new Nav_Article();
break;
case R.id.nav_about:
fragment = new Nav_AboutUs();
break;
case R.id.nav_suggest:
fragment = new Nav_Suggest();
break;
case R.id.nav_share:
fragment = new Nav_Share();
break;
case R.id.nav_rateApp:
fragment = new Nav_RateApp();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.navContent, fragment)
.addToBackStack(null)
.commit();
}
}, 350);
return true;
}
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
}
Home Fragment
public class Nav_Home extends Fragment implements View.OnClickListener{
SharedPreferences mSharedPref;
private SwipeRefreshLayout swipeRefresh_home;
private CardView item_homeTop_coupons, item_homeTop_draws, item_homeTop_event;
private LinearLayout layout_all_article, layout_all_999;
private ScrollView shimmer_home;
private List<Model_ListItem> listNewItems;
private RecyclerView recyclerView_item_home;
private List<Model_Article> articleList;
private RecyclerView recyclerView_article_home;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fetchItemsNew();
fetchArticlesNew();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_nav__home, container, false);
item_homeTop_coupons = view.findViewById(R.id.item_homeTop_coupons);
item_homeTop_draws = view.findViewById(R.id.item_homeTop_draws);
item_homeTop_event = view.findViewById(R.id.item_homeTop_event);
recyclerView_item_home = view.findViewById(R.id.recyclerView_item_home);
recyclerView_article_home = view.findViewById(R.id.recyclerView_article_home);
layout_all_article = view.findViewById(R.id.layout_all_article);
layout_all_999 = view.findViewById(R.id.layout_all_999);
swipeRefresh_home = view.findViewById(R.id.swipeRefresh_home);
shimmer_home = view.findViewById(R.id.shimmer_home);
item_homeTop_coupons.setOnClickListener(this);
item_homeTop_draws.setOnClickListener(this);
item_homeTop_event.setOnClickListener(this);
layout_all_999.setOnClickListener(this);
layout_all_article.setOnClickListener(this);
//first settngs
mSharedPref = PreferenceManager.getDefaultSharedPreferences(view.getContext());
String session_user_email = mSharedPref.getString("session_user_email","");
swipeRefresh_home.setRefreshing(true);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.item_homeTop_coupons:
startActivity(new Intent(getContext(), Page_Coupon.class));
break;
case R.id.item_homeTop_draws:
startActivity(new Intent(getContext(), Page_Draw.class));
break;
case R.id.item_homeTop_event:
startActivity(new Intent(getContext(), Page_Event.class));
break;
case R.id.layout_all_999:
//999 city search activity
startActivity(new Intent(getContext(), Page_SearchCity.class));
break;
case R.id.layout_all_article:
//article fragment
Fragment fragment;
FragmentManager fragmentManager = getFragmentManager();
fragment = new Nav_Article();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
break;
}
}
public void fetchItemsNew(){
listNewItems = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_ListItem>> call = api_service.fetchItemsNew();
call.enqueue(new Callback<List<Model_ListItem>>() {
#Override
public void onResponse(Call<List<Model_ListItem>> call, Response<List<Model_ListItem>> response) {
if(response.code() == 200){
listNewItems = response.body();
Adapter_HomeItem adapter_homeItem = new Adapter_HomeItem(getContext(), listNewItems);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_item_home.setHasFixedSize(true);
recyclerView_item_home.setLayoutManager(layoutManager);
recyclerView_item_home.setAdapter(adapter_homeItem);
SnapHelper helper = new LinearSnapHelper();
helper.attachToRecyclerView(recyclerView_item_home);
}
}
#Override
public void onFailure(Call<List<Model_ListItem>> call, Throwable t) {
}
});
}
public void fetchArticlesNew(){
articleList = new ArrayList<>();
API_Service api_service = Client.getRetrofitInstance().create(API_Service.class);
Call<List<Model_Article>> callArticle = api_service.fetchArticlesNew();
callArticle.enqueue(new Callback<List<Model_Article>>() {
#Override
public void onResponse(Call<List<Model_Article>> call, Response<List<Model_Article>> response) {
if(response.code() == 200){
articleList = response.body();
Adapter_HomeArticles adapter_homeArticles = new Adapter_HomeArticles(getContext(), articleList);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
recyclerView_article_home.setLayoutManager(layoutManager);
recyclerView_article_home.setHasFixedSize(true);
recyclerView_article_home.setAdapter(adapter_homeArticles);
}
}
#Override
public void onFailure(Call<List<Model_Article>> call, Throwable t) {
}
});
}
}
Firstly you must disable SwipeRefreshLayout spinning when successfully or not fetched data:
swipeRefresh_home.setRefreshing(false);
If you do not do this spinner will be spinning all the time.
Another problem is that you have one fragment and you try to assign to it Nav_Home fragment and Nav_Profile fragment.
Fragment fragment;
public void displayDefaultFragment() {
fragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).commit();
}
public void showProfileFragment() {
fragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, fragment).addToBackStack(null).commit();
}
Try to separate them and show like this:
Fragment homeFragment;
Fragment profileFragment;
public void displayDefaultFragment() {
homeFragment = new Nav_Home();
fragmentManager.beginTransaction().replace(R.id.navContent, homeFragment).commit();
}
public void showProfileFragment() {
profileFragment = new Nav_Profile();
fragmentManager.beginTransaction().replace(R.id.navContent, profileFragment).addToBackStack(null).commit();
}
I am trying to create an app. I want to change navigation drawer icon to back Arrow in Action Bar and when i open a fragment and go back to main activity when i click on back arrow in fragment Using the following code-
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener{
DrawerLayout mDrawerLayout;
ListView mDrawerList;
#SuppressWarnings("deprecation")
ActionBarDrawerToggle mDrawerToggle;
String mTitle="";
private final String TAG = this.getClass().getSimpleName();
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,NearbyPlace,FindMarker;
EditText editplace = null;
Button findbtn = null;
boolean firstRun = true;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for connectivity service
ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cManager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnected()) {
Toast.makeText(this, "Network is available ", Toast.LENGTH_SHORT).show();
AdView adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice("abc")
.build();
adView.loadAd(adRequest);
mFragment=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
else{
Toast.makeText(this, "Network is not available ", Toast.LENGTH_SHORT).show();
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
newFragment = new NetworkCheck();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
editplace = (EditText) findViewById(R.id.editplace);
findbtn = (Button) findViewById(R.id.findbtn);
setListnerOnWidget();
mTitle = (String) getTitle();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle( this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Select a menu");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.menu)
);
mDrawerList.setAdapter(adapter);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
displayView(position);
// Updating the action bar title
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new Help();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
newFragment = new ContactUs();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
transaction.addToBackStack(null);
getActionBar().setTitle("IQWINER");
try
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "Choose an action"));
}
catch(Exception e)
{ //e.toString();
}
break;
case 3:
newFragment = new Suggestion_Address();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "Suggestion Address button is clicked");
break;
}
}
});
}
private void setListnerOnWidget() {
// TODO Auto-generated method stub
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = editplace.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
}
}
};
findbtn.setOnClickListener(listener);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
//for back button
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(Gravity.START)){
mDrawerLayout.closeDrawer(Gravity.START);
}
else if(getFragmentManager().getBackStackEntryCount() > 1){
super.onBackPressed();
}
else{
if (exit){
finish(); // finish activity
}
else{
Toast.makeText(this, "Tap Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
}
I want to change navigation drawer icon to back arrow icon when i open a fragment and when i click on back arrow then go back to main activity from a fragment.
Thanks
Remove the below code :
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.menu)
);
mDrawerList.setAdapter(adapter);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
displayView(position);
// Updating the action bar title
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new Help();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 1:
newFragment = new ContactUs();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
transaction.addToBackStack(null);
getActionBar().setTitle("IQWINER");
try
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "Choose an action"));
}
catch(Exception e)
{ //e.toString();
}
break;
case 3:
newFragment = new Suggestion_Address();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "Suggestion Address button is clicked");
break;
}
}
});
and change it with below code:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
// This method will trigger on item Click of navigation menu
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
//Checking if the item is in checked state or not, if not make it in checked state
if (menuItem.isChecked()) menuItem.setChecked(false);
else menuItem.setChecked(true);
//Closing drawer on item click
drawerLayout.closeDrawers();
//Check to see which item was being clicked and perform appropriate action
switch (menuItem.getItemId()) {
//Replacing the main content with ContentFragment Which is our Inbox View;
case R.id.drawer_home:
txt_title.setText("Home");
Intent intent=new Intent(HomeActivity.this, HomeActivity.class);
startActivity(intent);
finish();
return true;
case R.id.drawer_artist:
txt_title.setText("Artists");
android.support.v4.app.FragmentManager fragmentManager=getSupportFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new ArtistsFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return true;
case R.id.drawer_myplaylist:
txt_title.setText("My Playlists");
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, new PlayListFragment());
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
return true;
default:
Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
return true;
}
}
});
Edit
xml:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:elevation="4dp"
android:layout_height="fill_parent"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<include
android:id="#+id/tool_bar"
layout="#layout/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
/>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/home">
//Your layout
</FrameLayout>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
android:background="#drawable/bg_all"
app:itemIconTint="#android:color/white"
app:itemTextColor="#android:color/white"
app:theme="#style/list_item_appearance"
app:menu="#menu/drawer_menu" >
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
getSupportFragmentManager().addOnBackStackChangedListener(
new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
if (getSupportFragmentManager()
.getBackStackEntryCount() > 0) {
getSupportActionBar()
.setDisplayHomeAsUpEnabled(true); // show
// back button
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
} else {
// show hamburger
getSupportActionBar()
.setDisplayHomeAsUpEnabled(false);
mDrawerToggle.syncState();
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout
.openDrawer(GravityCompat.START);
}
});
}
}
});
Use the following after mDrawerLayout.setDrawerListener(mDrawerToggle);
I am trying to create an app. I want to go back to my main layout from a fragment when click on back button in the fragment Using the following code-
public class MainActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener{
DrawerLayout mDrawerLayout;
ListView mDrawerList;
#SuppressWarnings("deprecation")
ActionBarDrawerToggle mDrawerToggle;
String mTitle="";
private final String TAG = this.getClass().getSimpleName();
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
LatLng latLng;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,NearbyPlace,FindMarker;
EditText editplace = null;
Button findbtn = null;
boolean firstRun = true;
private Boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for connectivity service
ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cManager.getActiveNetworkInfo();
if (nInfo != null && nInfo.isConnected()) {
Toast.makeText(this, "Network is available ", Toast.LENGTH_SHORT).show();
AdView adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice("abc")
.build();
adView.loadAd(adRequest);
mFragment=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
}
else{
Toast.makeText(this, "Network is not available ", Toast.LENGTH_SHORT).show();
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
newFragment = new NetworkCheck();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
editplace = (EditText) findViewById(R.id.editplace);
findbtn = (Button) findViewById(R.id.findbtn);
setListnerOnWidget();
mTitle = (String) getTitle();
// Getting reference to the DrawerLayout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle( this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close){
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Select a menu");
invalidateOptionsMenu();
}
};
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.setDrawerIndicatorEnabled(true);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getBaseContext(),
R.layout.drawer_list_item ,
getResources().getStringArray(R.array.menu)
);
mDrawerList.setAdapter(adapter);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
displayView(position);
// Updating the action bar title
String[] menu = getResources().getStringArray(R.array.menu);
mTitle = menu[position];
mDrawerLayout.closeDrawer(mDrawerList);
}
private void displayView(int position) {
// TODO Auto-generated method stub
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new Help();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "help button is clicked");
break;
case 1:
newFragment = new ContactUs();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "ContactUs button is clicked");
break;
case 2:
transaction.addToBackStack(null);
try
{ Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
String sAux = "\nLet me recommend you this application\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "Choose an action"));
}
catch(Exception e)
{ //e.toString();
}
Log.e(TAG, "share button is clicked");
break;
case 3:
newFragment = new Suggestion_Address();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
Log.e(TAG, "Suggestion Address button is clicked");
break;
}
}
});
}
Please tell me how to go back to my main layout from a fragment layout when click on back button..
Thanks
Try this in your activity
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStackImmediate();
} else {
super.onBackPressed();
}
}
I'm trying to add an button icon in the upper right hand side of action bar and I follow this tutorial
Claims1.java
public class Claims1 extends Fragment {
long fk;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
fk = bundle.getLong("ab");
View claims = inflater.inflate(R.layout.claims, container, false);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
ImageView imageView = new ImageView(actionBar.getThemedContext());
imageView.setScaleType(ImageView.ScaleType.CENTER);
imageView.setImageResource(R.mipmap.create);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
ActionBar.LayoutParams.WRAP_CONTENT,
ActionBar.LayoutParams.WRAP_CONTENT, Gravity.RIGHT
| Gravity.CENTER_VERTICAL);
layoutParams.rightMargin = 40;
imageView.setLayoutParams(layoutParams);
actionBar.setCustomView(imageView);
return claims;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// get list items from strings.xml
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.nav_drawer_items);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.mipmap.ic_drawer,
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(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// 2.1 create ActionBarDrawerToggle
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[5];
drawerItem[0] = new ObjectDrawerItem(R.mipmap.timesheet, "Time Sheet");
drawerItem[1] = new ObjectDrawerItem(R.mipmap.claims, "Claims");
drawerItem[2] = new ObjectDrawerItem(R.mipmap.project_icon, "Project");
drawerItem[3] = new ObjectDrawerItem(R.mipmap.report, "Report");
drawerItem[4] = new ObjectDrawerItem(R.mipmap.view, "View");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
}
#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);
mDrawerToggle.syncState();
}
public 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:
fragment=new Information();
break;
case 1:
fragment=new Claims1();
Bundle bundle=new Bundle();
bundle.putLong("ab",WorkDetailsTable.ab);
fragment.setArguments(bundle);
break;
case 2:
fragment=new Project();
break;
case 3:
fragment=new Report();
break;
case 4:
fragment=new ViewView();
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);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
However, my app crashed. Do I need to add anything in my claims1.xml?
11-15 13:22:27.384 4199-4199/com.example.project.project E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.project.project, PID: 4199
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.app.ActionBar.getDisplayOptions()' on a null object reference
at com.example.project.project.Claims1.onCreateView(Claims1.java:26)
at android.app.Fragment.performCreateView(Fragment.java:2220)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
(Claims1.java:26)
actionBar.setDisplayOptions(actionBar.getDisplayOptions()
| ActionBar.DISPLAY_SHOW_CUSTOM);
You are using wrong getActionBar method.
You are using AppCompatActivity so action bar is from supported library.
You should use ((AppCompatActivity) getActivity()).getSupportActionBar();
If you not make cast getActionBaris asking about android.app.ActionBar
but using AppCompatActivity you need to ask about android.support.v7.app.ActionBar
I am building an simply webview app with mDrawer menu, and it work's like a charm on 3.0+ android, but i want it to work with versions under 3. I have read about v4 support and i added it to the project. Application was a Activity then i changed to FragmentActivity because off support library . Sorry for my English.
Here's the code.
public class MainActivity extends FragmentActivity {
private LayoutInflater mInflater;
private DrawerLayout mDrawerLayout;
WebView browser;
// ListView represents Navigation Drawer
private ListView mDrawerList;
// ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
private ActionBarDrawerToggle mDrawerToggle;
private String mTitle = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView browser = (WebView) findViewById(R.id.webView1);
browser.loadUrl("");
browser.setWebViewClient(new WebViewClient());
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.drawer_list);
// Getting reference to the ActionBarDrawerToggle
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open,
R.string.drawer_close) {
/** Called when drawer is closed */
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
/** Called when a drawer is opened */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle("Menu");
invalidateOptionsMenu();
}
};
browser.setOnKeyListener(new OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
// Setting DrawerToggle on DrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);
// Creating an ArrayAdapter to add items to the listview mDrawerList
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(),
R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));
// Setting the adapter on mDrawerList
mDrawerList.setAdapter(adapter);
// Enabling Home button
getActionBar().setHomeButtonEnabled(true);
// Enabling Up navigation
getActionBar().setDisplayHomeAsUpEnabled(true);
// Setting item click listener for the listview mDrawerList
mDrawerList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Getting an array of rivers
String[] menuItems = getResources().getStringArray(R.array.menus);
// Currently selected river
mTitle = menuItems[position];
// Creating a fragment object
// Passing selected item information to fragment
Bundle data = new Bundle();
data.putInt("position", position);
data.putString("url", getUrl(position));
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
if(getFragmentManager().getBackStackEntryCount() == 0) finish();
}
});
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
});
}
The problem is in
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
if(getFragmentManager().getBackStackEntryCount() == 0) finish();
}
});
The method addOnBackStackChangedListener(FragmentManager.OnBackStackChangedListener) in the type FragmentManager is not applicable for the arguments (new FragmentManager.OnBackStackChangedListener(){})
You're importing the wrong FragmentManager.OnBackStackChangedListener.
What you have
import android.app.FragmentManager.OnBackStackChangedListener;
What you should have
import android.support.v4.app.FragmentManager.OnBackStackChangedListener;
use getSupportFragmentManager() instead of getFragmentManager.
fragmentManager.addOnBackStackChangedListener(new OnBackStackChangedListener() {
public void onBackStackChanged() {
if(getSupportFragmentManager().getBackStackEntryCount() == 0)
finish();
}
});