fragments - how to use them with activities that require actions? - android

First - apologies for the newbie question.
I'm trying to implement a Navigation Drawer that will be used across my app. To start, I've followed the Android tutorial and created a basic navigation which changes a with Fragments.
I can pass a framelayout id and fragment to FragmentTransaction. It works great.
I decided to create a new login activity with the default android files (In Android Studio: going to new - activity - login activity ). This is what's confusing me. My questions are:
Can I create a fragment of the login activity where the actions in LoginActivity will work? It looks like the fragment will create a view based on the layout passed, but the methods used in LoginActivity won't work?
If creating a fragment does not work for the login activity, what would be the cleanest way to ensure the navigation works when switching activities? The Navigation Drawer only works when on the main activity; switching to other activities (via Intent) causes the app to lose the navigation drawer actions. The image of the actionbar/navigation drawer remains.
Here's some of my code in MainActivity ... maybe I'm missing something that is causing the navigation drawer to stop functioning when switching activities by Intent?
(Note: LoginActivity extends MainActivity in the LoginActivity class)
Thanks in advance for any direction / advice!
public class MainActivity extends ActionBarActivity {
private NavigationDrawerFragment mNavigationDrawerFragment;
//USER DATA
public String mUserID;
public String mToken;
public String mProgramData;
//NAVIGATION DRAWER
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private String[] mTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mActionBarDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
// get list items for nav
mTitles = getResources().getStringArray(R.array.nav_menu);
//drawer widget
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
//listview of left drawer
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// Set up the drawer.
mDrawerList.setAdapter(new ArrayAdapter<>(this,
R.layout.drawer_list_item, mTitles));
//set onclicklistener on the each list item of menu options
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// some styling...
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
//enables action bar app behavior
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// ties drawerlayout and actionbar for navigation drawers
mActionBarDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
// different titles for the drawer actions
public void onDrawerClosed(View drawerView) {
getSupportActionBar().setTitle(mTitle);
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
}
};
// set drawer toggle as the drawer listener
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
selectItem(position);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#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();
if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch(id) {
case R.id.action_home:
Intent home = new Intent(this, MainActivity.class);
this.startActivity(home);
break;
case R.id.action_login:
Intent login = new Intent(this, LoginActivity.class);
this.startActivity(login);
break;
}
return super.onOptionsItemSelected(item);
}
EDIT
Thanks for your help so far in guiding me with my issue.
Unfortunately I don't think I'm asking the right question, but maybe viewing the LoginActivity code from Android Studio would help.
This is part of LoginActivity:
public class LoginActivity extends MainActivity implements LoaderCallbacks<Cursor> {
private UserLoginTask mAuthTask = null;
// UI references.
private AutoCompleteTextView mUserIDView;
private EditText mPasswordView;
private View mProgressView;
private View mLoginFormView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mUserIDView = (AutoCompleteTextView) findViewById(R.id.email);
populateAutoComplete();
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
mEmailSignInButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
attemptLogin();
}
});
mLoginFormView = findViewById(R.id.login_form);
mProgressView = findViewById(R.id.login_progress);
}
private void populateAutoComplete() {
getLoaderManager().initLoader(0, null, this);
}
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin() {
if (mAuthTask != null) {
return;
}
// Reset errors.
mUserIDView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
String email = mUserIDView.getText().toString();
String password = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password, if the user entered one.
if (TextUtils.isEmpty(password)) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address or ID.
if (TextUtils.isEmpty(email)) {
mUserIDView.setError(getString(R.string.error_field_required));
focusView = mUserIDView;
cancel = true;
} else if (!isEmailValid(email) && !isIDValid(email)) {
mUserIDView.setError(getString(R.string.error_invalid_email));
focusView = mUserIDView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
showProgress(true);
mAuthTask = new UserLoginTask(email, password);
mAuthTask.execute((Void) null);
}
}
private boolean isEmailValid(String email) {
//TODO: Replace this with your own logic
return email.contains("#");
}
private boolean isIDValid(String email) {
//TODO: Replace this with your own logic
return email.length() == 6;
}
[continued]...........
I'll create a simple fragment of LoginActivity called menu1_Fragment:
public class menu1_Fragment extends android.support.v4.app.Fragment {
View rootview;
public View onCreateView(LayoutInflater inflater, ViewGroup view, Bundle savedInstanceState) {
rootview = (ViewGroup)inflater.inflate(R.layout.activity_login, null);
return rootview;
}
}
If i'm correct (hopefully I'm wrong!) the fragment is replaced with the View (menu1_Fragment). The View cannot have actions (like clicking the login button to send a httppost request).
Also, could you explain why onOptionsItemSelected in MainActivity breaks the navigationdrawer (drawer becomes unclickable. also cannot swipe right to pull it up). Intent launches an activity (LoginActivity), but only the drawer in apperance shows.

to hide also ActionBar icons you can do like:
#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);
}
}
To replace main fragment when you click an item from the drawable menu list i see you have used selectItem(position) method, however that method is never declared on your code. To do that also you can do something like:
private void selectItem(int position){
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 1:
fragment = new TestFragment();
break;
case 2:
fragment = new TestFragment2();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
setTitle(navMenuTitles[position]);
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}

I am giving you a example with multiple activities defined as fragment and called using MainActivity, Hope you will get your solution among it..
MainActivity.java
package com.example.fragmentdemo1;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements
OnItemClickListener {
MainActivity activity;
private ListView lv;
private ArrayList<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity = this;
lv = (ListView) findViewById(R.id.listView);
list.add("First");
list.add("Second");
list.add("Third");
list.add("Forth");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(activity,
android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (position) {
case 0:
Fragment1 f1 = new Fragment1();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.addToBackStack(null);
transaction.replace(R.id.container, f1).commit();
break;
case 1:
Fragment2 f2 = new Fragment2();
FragmentTransaction transaction2 = getSupportFragmentManager()
.beginTransaction();
transaction2.addToBackStack(null);
transaction2.replace(R.id.container, f2).commit();
break;
case 2:
Toast.makeText(activity, "" + position, 1000).show();
Fragment3 f3 = new Fragment3();
FragmentTransaction transaction3 = getSupportFragmentManager()
.beginTransaction();
transaction3.addToBackStack(null);
transaction3.replace(R.id.container, f3).commit();
break;
case 3:
Fragment4 f4 = new Fragment4();
FragmentTransaction transaction4 = getSupportFragmentManager()
.beginTransaction();
transaction4.addToBackStack(null);
transaction4.replace(R.id.container, f4).commit();
break;
default:
break;
}
}
#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();
switch (id) {
case android.R.id.home:
finish();
break;
default:
break;
}
return false;
}
}
Fragment1.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment1 extends android.support.v4.app.Fragment{
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView1);
view = (ViewGroup) inflater.inflate(R.layout.fragment1, null);
return view;
}
}
Fragment2.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment2 extends Fragment {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView2);
view = (ViewGroup) inflater.inflate(R.layout.fragment2, null);
return view;
}
}
Fragment3.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment3 extends Fragment {
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView3);
view =(ViewGroup)inflater.inflate(R.layout.fragment3, null);
return view;
}
}
Fragment4.java
package com.example.fragmentdemo1;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Fragment4 extends Fragment{
TextView tv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup view,
Bundle savedInstanceState) {
tv =(TextView)view.findViewById(R.id.textView4);
view = (ViewGroup)inflater.inflate(R.layout.fragment4, null);
return view;
}
}
NOTE : If you want to use method from Fragment class to MainActivity, then you can make it public static, and you can use that method directly by it's class name like Fragment1.countData().
This demo also apply for Navigation drawer.

Related

Passing values from main activity to another fragment

This is my Main Activity.class file . It contains a navigation drawer where i am using a login section. In the login fragment if the user log in successfully then an int flag is set to 1. which I am receiving here. Now I want to send this value to the services fragment. But I am unable to understand how to do so.
MainActivity.class
package net.simplifiedcoding.navigationdrawerexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.design.widget.NavigationView;
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.MenuItem;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
#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.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
String auth= getIntent().getStringExtra("authentication");
//initializing the fragment object which is selected
switch (itemId) {
case R.id.nav_menu1:
fragment = new Services(auth);
break;
case R.id.nav_menu2:
fragment = new Login();
break;
case R.id.nav_share:
fragment = new Share();
break;
case R.id.nav_rate:
fragment = new Rate();
break;
}
//replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
//calling the method displayselectedscreen and passing the id of selected menu
displaySelectedScreen(item.getItemId());
//make this method blank
return true;
}
}
Services.class
package net.simplifiedcoding.navigationdrawerexample;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Services extends Fragment {
String itemValue;
public Services(String auth) {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//returning our layout file
//change R.layout.yourlayoutfilename for each of your fragments
return inflater.inflate(R.layout.fragment_services, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//you can set the title for your toolbar here for different fragments different titles
getActivity().setTitle("Our Services");
final ListView listView = (ListView) view.findViewById(R.id.listView);
String[] values = new String[]{"Allergist", "Cardiologist", "Dermatologist","Endocrinologist","Gastroenterologists","Neurologist","OBGYN","Oncologists","Ophthalmologists","Pediatrician","Psychologist"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemPosition=position;
itemValue= (String) listView.getItemAtPosition(position);
Intent intent= new Intent((Context)getContext(),Doctor.class);
startActivity(intent);
}
});
}
}
It is saying the error as Avoid non default constructors in fragments. Use Fragment#setArguments(Bundle) instead.
Please help guys. I am a novice in android app development.
From Activity you send data with intent as:
Bundle bundle = new Bundle();
bundle.putString("edttext", "From Activity");
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("edttext");
return inflater.inflate(R.layout.fragment, container, false);
}
Also You can access activity data from fragment:
Activity:
public class MyActivity extends Activity {
private String myString = "hello";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
...
}
public String getMyData() {
return myString;
}
}
Fragment:
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
MyActivity activity = (MyActivity) getActivity();
String myDataFromActivity = activity.getMyData();
return view;
}
}
Use following flow
Bundle bundle = new Bundle(); //declare global
case R.id.nav_menu1:
fragment = new Services(auth);
bundle.putString("value", "3");// use from static variable in activity
break;
then
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.setArguments(bundle);
ft.commit();} }
then fragment get
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String value = getArguments().getString("value"); // you can get 3
return inflater.inflate(R.layout.fragment, container, false);
}
In Activity, your create:
public String myData;
myData = "YourData";
public String getData(){
return myData;
}
In Fragment:
MainActivity activity = (MainActivity)getActivity;
String b = activity.getData();

how to change the Title in Navigation Drawer

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");

Android: Starting a navigation drawer from an activity

There are lots of question which are similar to mine but I couldn't find any solution in those answers.
My program first shows a splash screen than comes to a log-in screen. After the user logs in I want to call the navigation drawer because my main screen and profile screen are in the navigation drawer as a fragment. So basically iI am trying to call a fragment which is a part of navigation drawer, from an activity.
Here is how I try to call the fragment;
private void loguserIn(User returnedUser){
userLocalStore.storeUserData(returnedUser);
userLocalStore.setUserLoggedIn(true);
Intent intent = new Intent(this,userprofile.class);
startActivity(intent);
}
But when i call this method it force closes.
Here is the userprofile fragment;
package com.okanyakit.watchme;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
/**
* Created by okan on 4/23/2015.
*/
public class userprofile extends android.support.v4.app.Fragment implements View.OnClickListener{
View rootview;
Button logoutbutton;
EditText regusername, regpassword, regemail, regphonenumber, regbloodtype, regbirthday, regaddress;
UserLocalStore userLocalStore;
Context context;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootview = inflater.inflate(R.layout.userprofile_layout,container,false);
regusername = (EditText)rootview.findViewById(R.id.regusername);
regpassword = (EditText)rootview.findViewById(R.id.regpassword);
regemail = (EditText)rootview.findViewById(R.id.regemail);
regphonenumber = (EditText)rootview.findViewById(R.id.regphonenumber);
regbloodtype = (EditText)rootview.findViewById(R.id.regbloodtype);
regbirthday = (EditText)rootview.findViewById(R.id.regbirthday);
regaddress = (EditText)rootview.findViewById(R.id.regaddress);
logoutbutton = (Button)rootview.findViewById(R.id.regbutton);
logoutbutton.setOnClickListener(this);
userLocalStore = new UserLocalStore(this);
return rootview;
}
#Override
public void onStart() {
super.onStart();
if (authenticate()== true)
{
displayUserDetails();
}
else{
Intent intent = new Intent(getActivity(),loginscreen.class);
startActivity(intent);
}
}
private void displayUserDetails()
{
User user = userLocalStore.getLoggedInUser();
regusername.setText(user.username);
regemail.setText(user.email);
regphonenumber.setText(user.phonenumber);
regbloodtype.setText(user.bloodtype);
regaddress.setText(user.address);
}
private boolean authenticate()
{
return userLocalStore.getuserloogedin();
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.logoutbutton:
userLocalStore.clearUserData();
userLocalStore.setUserLoggedIn(false);
break;
}
}
}
Here is the slide menu ;
package com.okanyakit.watchme;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class slidemenu extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slidemenu);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objfragment = null;
switch (position) {
case 0:
objfragment = new mainscreen();
break;
case 1:
objfragment = new userprofile();
break;
case 2:
objfragment = new usermessage();
break;
case 3:
objfragment = new alarmsettings();
break;
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objfragment)
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
case 4:
mTitle = getString(R.string.title_section4);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.slidemenu, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_slidemenu, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((slidemenu) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
Andr here is the navigationdrawer class
package com.okanyakit.watchme;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).commit();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
I don't know what is the main cause of this so tried to put everything that is involved in here.
I think this should work for you.
DrawerLayout mLayout = (DrawerLayout) mNavigationDrawerFragment.findViewById(R.id.drawer_layout);
mLayout.openDrawer(mLayout);
You cannot call a fragment with Intents. An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity.
You can call your fragment with
ExampleFragment fragment = (ExampleFragment)getFragmentManager.getfindFragmentById(R.id.example_fragment);
To put the fragment in your activity, use this method in your oncreate of your activity:
if (savedInstance == null)
{
getFragmentManger().beginTransaction().Add(R.id.container, new ExampleFragment()).commit();
}
where R.id.container is the ID in your activity layoutfile of the placeholder in which you want to place your fragments.

Can't Go Back in Webviews

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

Altering what will appear on different fragments (Navigation Drawer)

I'm back on again. My last attempt at the Navigation Drawer failed, so I have started it with fragments (going much better this time). Anyways, I have got to the point where the fragments are loading etc, but I have no idea where it edits what appears in each fragment.
I was assuming there was a separate thing for each fragment, but I can't find it, if you guys can help that would be great.
So basically, my question is, how to tell the different fragments what to display? I have a feeling it is in the onCreateView method but I'm not sure..
Here's my code:
package com.example.android.navigationdrawerexample;
import java.util.Locale;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private DrawerLayout DrawerLayout;
private ListView DrawerList;
private ActionBarDrawerToggle DrawerToggle;
private CharSequence DrawerTitle;
private CharSequence Title;
private String[] pageArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Title = DrawerTitle = getTitle();
pageArray = getResources().getStringArray(R.array.pageArray);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
DrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
DrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
DrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, pageArray));
DrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
DrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
DrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace standard image in action bar */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(Title);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(DrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerLayout.setDrawerListener(DrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = DrawerLayout.isDrawerOpen(DrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (DrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listener for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
// update the main content by replacing fragments
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
DrawerList.setItemChecked(position, true);
setTitle(pageArray[position]);
DrawerLayout.closeDrawer(DrawerList);
}
#Override
public void setTitle(CharSequence title) {
Title = title;
getActionBar().setTitle(Title);
}
/**
* 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.
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
DrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PageFragment extends Fragment {
public static final String ARG_PAGE_NUMBER = "page_number";
public PageFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int pgNum = getArguments().getInt(ARG_PAGE_NUMBER);
String planet = getResources().getStringArray(R.array.pageArray)[pgNum];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
If you can help me out, that would be great :)
Look in your selectItem method, which is called whenever a tab is selected.
It currently creates a new PageFragment instance:
Fragment fragment = new PageFragment();
And then passes the ID of the selected item as an argument:
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_NUMBER, position);
fragment.setArguments(args);
That is to say, no matter which item is selected, PageFragment is instantiated, just with different arguments.
In PageFragment's onCreateView method, this argument is retrieved and used to determine which planet to display:
int pgNum = getArguments().getInt(ARG_PAGE_NUMBER);
String planet = getResources().getStringArray(R.array.pageArray)[pgNum];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
So, that is 'where it edits what appears in each fragment'.
If you want to display a different fragment for each item in the drawer (probably a fairly common use case) then I would use a switch statement:
private void selectItem(int position) {
Fragment fragment;
// Select a different fragment based on which tab has been selected
switch (position) {
case 0:
fragment = new TopDrawerItemFragment();
break;
case 1:
fragment = new SecondDrawerItemFragment();
break;
}
// Replace the fragment
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mTabTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
TopDrawerItemFragment and SecondDrawerItemFragment could be inner classes (like PageFragment) or separate Java class files.
You're selectItem method is setting up your fragment views. The lines
Fragment fragment = new PageFragment();
Bundle args = new Bundle();
args.putInt(PageFragment.ARG_PAGE_NUMBER, position);
fragment.setArguments(args);
are creating the new fragment and setting its data where as the next 2 lines in the method
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
are changing the app's view to that of the fragment's (basically displaying that fragment). As for the fragment's view, the fragment'w own onCreateView method issetting up its view. Hopefully that helps

Categories

Resources