虽然我已经确定了 getActionBar()setDisplayHomeAsUpEnabled(真)。 getActionBar()setHomeButtonEnabled(真)。 当我触摸导航图标ic_drawer时,导航窗格不会显示。
以下是代码: 包com.happyshare;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
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.util.Log;
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.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.android.Facebook;
import com.facebook.model.GraphUser;
import com.happyshare.utilities.RequestTask;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
private static final String TAG = "Main Activity";
private static final String PREFS_NAME = "MyPreferencesFile";
SharedPreferences settings = null;
String strUserName = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "Inside onCreate method");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settings = getSharedPreferences(PREFS_NAME, 0);
if(!isLoggedIn()){
InitializeUI();
TextView tv = (TextView) findViewById(R.id.user_name);
tv.setText("Hello " + settings.getString("UserName", "Guys"));
}
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.planets_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.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
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
final Button btnSearch = (Button) findViewById(R.id.buttonSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Perform action on click
new RequestTask().execute("http://api.brfares.com/querysimple?orig=LDS&dest=OXF");
//Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);
// currentContext.startActivity(activityChangeIntent);
//PresentActivity.this.startActivity(activityChangeIntent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
Log.d(TAG, "Inside onCreateOptionsMenu method");
MenuInflater mif = getMenuInflater();
//mif.inflate(R.menu.action_bar, menu);
mif.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item){
Log.d(TAG, "Inside onOptionsItemSelected method");
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.bookings_icon:
facebookLoginDialog();
break;
case R.id.person_icon:
facebookLoginDialog();
break;
case R.id.messages_icon:
facebookLoginDialog();
break;
default:
;
}
return true;
}
public boolean isLoggedIn() {
Log.d(TAG, "Inside isLoggedIn method");
Session session = Session.getActiveSession();
return (session != null && session.isOpened());
}
private void facebookLoginDialog(){
Log.d(TAG, "Inside facebookLoginDialog method");
if(!isLoggedIn()){
new AlertDialog.Builder(this)
.setTitle("This function requires Happyshare login.")
.setMessage("Do you want to continue?")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
} })
.setPositiveButton("Login", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
facebookLogin();
}
}).show();
}
}
private void facebookLogoutDialog(){
Log.d(TAG, "Inside facebookLogoutDialog method");
if(isLoggedIn()){
new AlertDialog.Builder(this)
.setTitle("Are you sure you want to log out.")
.setMessage("Do you want to continue?")
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
} })
.setPositiveButton("Log Out", new DialogInterface.OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "**********Before if******************");
Facebook fb = new Facebook(getResources().getString(R.string.app_id));
Log.d(TAG, "------------------0--------------------");
Session session = Session.getActiveSession();
Log.d(TAG, "------------------1--------------------");
session.close();
Log.d(TAG, "------------------2--------------------");
//try {
//should be called on separate thread
//fb.logout(getApplicationContext());
MainActivity.this.finish();
finish();
Log.d(TAG, "Starting Intent for logging out.");
startActivity(new Intent(getApplicationContext(), LogoutActivity.class));
/*} catch (MalformedURLException e) {
Log.e(TAG, "Got MalformedURLException::"+e.getMessage());
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, "Got IOException::"+e.getMessage());
e.printStackTrace();
}*/
}
}).show();
}
}
private void facebookLogin(){
Log.d(TAG, "Inside facebookLogin method");
//start Facebook Login
Session.openActiveSession(this, true, new Session.StatusCallback() {
// callback when session changes state
@SuppressWarnings("deprecation")
@Override
public void call(Session session, SessionState state, Exception exception) {
Log.d(TAG, "Inside call method");
if (session.isOpened()){
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
@Override
public void onCompleted(GraphUser user, Response response) {
if (user != null){
strUserName = user.getName();
SharedPreferences.Editor editor = settings.edit();
editor.putString("UserName", strUserName);
editor.commit();
// sets username
TextView user_name = (TextView) findViewById(R.id.user_name);
user_name.setText("Hello " + strUserName);
// sets the facebook verified image here
ImageView profileVerifiedImageView = (ImageView) findViewById(R.id.profile_verified);
profileVerifiedImageView.setImageResource(R.drawable.facebook_verified);
// sets the phone verified image here
ImageView phoneVerifiedImageView = (ImageView) findViewById(R.id.phone_verified);
phoneVerifiedImageView.setImageResource(R.drawable.phone_not_verified);
// view that in turn displays the profile picture.
/*String userID = null;
userID = user.getId();
Log.i(TAG, "The userid is::"+userID);
String strImageURL = "https://graph.facebook.com/" + userID + "/picture?type=large";
mImageView = (ImageView) findViewById(R.id.profile_picture);
Bitmap bitmap = (Bitmap) new DownloadImageTask().doInBackground(strImageURL);
mImageView.setImageBitmap(bitmap);*/
}
}
});
}
}
});
}
/*private class DownloadImageTask extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... params) {
String strURL = null;
try {
strURL = params[0].toString();
Log.i(TAG, "Image URL is::"+strURL);
URL imageURL = new URL(strURL);
return BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
Log.e("TAG", "*************Error in retrieving the profile image**************");
}
return null;
}
}*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
Log.d(TAG, "Inside onActivityResult method");
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
}
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
Log.d(TAG, "Inside onPrepareOptionsMenu method");
// If the nav drawer is open, hide action items related to the content view
return super.onPrepareOptionsMenu(menu);
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Log.d(TAG, "Inside selectItem method");
// update the main content by replacing fragments
Fragment fragment = new PlanetFragment();
Bundle args = new Bundle();
args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
Log.d(TAG,"Inside select item::"+position);
switch(position){
case 0 :
facebookLoginDialog();
break;
case 1 :
facebookLoginDialog();
break;
case 2 :
facebookLoginDialog();
break;
case 3 :
facebookLoginDialog();
break;
case 6 :
facebookLogoutDialog();
break;
default:
;
}
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(mPlanetTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
Log.d(TAG, "Inside setTitle method");
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
Log.d(TAG, "Inside onPostCreate method");
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(TAG, "Inside onConfigurationChanged method");
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
//setContentView(R.layout.activity_main);
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "Inside onCreateView method");
View rootView = null;
/*View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.planets_array)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
ImageView imageViewFragment = (ImageView) rootView.findViewById(R.id.image);
imageViewFragment.setImageResource(imageId);
//imageViewFragment.setBackgroundColor(Color.TRANSPARENT);
getActivity().setTitle(planet);
*/
return rootView;
}
}
// used in onCreate() and onConfigurationChanged() to set up the UI elements
public void InitializeUI()
{
// sets the facebook verified image here
ImageView profileVerifiedImageView = (ImageView) findViewById(R.id.profile_verified);
profileVerifiedImageView.setImageResource(R.drawable.facebook_verified);
// sets the phone verified image here
ImageView phoneVerifiedImageView = (ImageView) findViewById(R.id.phone_verified);
phoneVerifiedImageView.setImageResource(R.drawable.phone_not_verified);
}
}