Я использую общий ящик навигации для разных действий, где я расширяю BaseActivity, хотя он работает нормально, но я не могу открыть ящик, если я нажал кнопку "Назад", чтобы перейти к предыдущему действию.
Это мой код:
public class BaseActivity extends ActionBarActivity {
public static DrawerLayout mDrawerLayout;
public static ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
protected RelativeLayout _completeLayout, _activityLayout;
// nav drawer title
private CharSequence mDrawerTitle;
Context context;
// used to store app title
private CharSequence mTitle;
ImageView viewImage;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
private TextView tv_user_name;
private ProfilePictureView profilepic;
CallbackManager callbackManager;
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_base);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
callbackManager = CallbackManager.Factory.create();
// --------- login = (LoginButton)findViewById(R.id.login_button);
// profilepic = (ProfilePictureView)findViewById(R.id.fb_profile_pic);
// fetchDetailsViaFb();
}
public void setNavigationHeader() {
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.navigation_drawer_header, null, false);
mDrawerList.addHeaderView(listHeaderView);
viewImage = (ImageView) findViewById(R.id.profileImage);
tv_user_name=(TextView) findViewById(R.id.tv_user_name);
tv_user_name.setTextColor(Color.WHITE);
profilepic = (ProfilePictureView)findViewById(R.id.fb_profile_pic);
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items
if (navMenuIcons == null) {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i]));
}
} else {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i],
navMenuIcons.getResourceId(i, -1)));
}
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, null, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
setNavigationHeader();
}
@Override
public void onStart() {
super.onStart();
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"Base Page",
Uri.parse("http://host/path"),
Uri.parse("android-app://android.sit.findpro/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
@Override
public void onStop() {
super.onStop();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"Base Page",
Uri.parse("http://host/path"),
Uri.parse("android-app://android.sit.findpro/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
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);
}
/**
* Displaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
switch (position) {
case 0:
if(LogInActivity.userLoginViaFb){
profilepic.setVisibility(View.VISIBLE);
viewImage.setVisibility(View.GONE);
fetchDetailsViaFb();
}
viewImage.setVisibility(View.VISIBLE);
profilepic.setVisibility(View.GONE);
selectImage();
/* editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeToBase64(yourBitmap));
editor.commit();*/
break;
case 1:
Toast.makeText(BaseActivity.this, "Coming Soon", Toast.LENGTH_SHORT).show();
break;
case 2:
viewImage.setVisibility(View.VISIBLE);
selectImage();
break;
case 3:
Toast.makeText(BaseActivity.this, "Coming Soon", Toast.LENGTH_SHORT).show();
break;
case 4:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text that will be shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
break;
default:
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
@Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle sttate after onResoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void fetchDetailsViaFb(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if (json != null) {
String name = json.getString("name");
tv_user_name.setText(Html.fromHtml(name));
profilepic.setProfileId(json.getString("id"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
private void selectImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
builder.setTitle("Choose Profile Pic");
builder.setItems(new CharSequence[]{"Take a Photo", "Choose from Gallery", "Cancel"},
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent1, CAPTURE_IMAGE);
break;
case 1:
// GET IMAGE FROM THE GALLERY
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
break;
case 2:
dialog.dismiss();
default:
break;
}
}
});
builder.show();
profilepic.setVisibility(View.GONE);
}
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
System.out.println("path" + selectedImagePath);
viewImage.setImageBitmap(decodeFile(selectedImagePath));
PreferenceHandler.encodeToBase64(decodeFile(selectedImagePath)); //uy7igyoiugo
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
Toast.makeText(this,"path" + selectedImagePath,Toast.LENGTH_LONG).show();
System.out.println("path" + selectedImagePath);
viewImage.setImageBitmap(decodeFile(selectedImagePath));
String img= PreferenceHandler.encodeToBase64(decodeFile(selectedImagePath));//uyiyuogo
PreferenceHandler.writeString(BaseActivity.this,PreferenceHandler.PROFILE_IMAGE,img);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
/* We can override onBackPressed method to toggle navigation drawer*/
@Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}else {
// mDrawerLayout.openDrawer(mDrawerList);
super.onBackPressed();
}
}
}