0

I want to define an up button for my android application to go to parent activity. From some resources I found this code when up-button clicked:

NavUtils.navigateUpFromSameTask(getActivity());

But I had a problem and it was that my activity needs some data for creation (Intent extras) and for this reason I replaced with this code:

getActivity().finish();

But some feeling tells me this is not a correct way for reaching to parent activity and maybe I will face to some runtime errors later. What do you think what should I do?

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
Reza Abbasi
  • 1,521
  • 2
  • 15
  • 21

2 Answers2

1
  Intent myIntent = new Intent(sourceActivity.this,targetActivity.class);
  myIntent.putExtra("NameKey", yourValue); // for send a Value with a key name. yourValue can be every type value
  startActivity(myIntent);
  this.finish();
  // and for receive value from target activity
  Bundle extraGet = getIntent().getExtras();
  String receiveValue = extraGet.getString("NameKey");

also you can define public static your variable that can use it to every class and activities

i think you want this:

 Intent intent = NavUtils.getParentActivityIntent(this);
 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 NavUtils.navigateUpTo(this, intent); 
Milad gh
  • 211
  • 1
  • 11
0
//this function can used for every key on Phone that pressed
public boolean onKeyDown(int keyCode, KeyEvent event) {
          if(keyCode==event.KEYCODE_VOLUME_UP){
                    // On Click KEYCODE_VOLUME_UP Commands
                    // here, every code want to execute
                    }
          return super.onKeyDown(keyCode, event);
          }

Update (that you want ;-) ) in onCreate:

getActionBar().setDisplayHomeAsUpEnabled(true);

in main class :

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        Toast.makeText(getApplicationContext(), "Khosh begzare", Toast.LENGTH_SHORT).show();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
Milad gh
  • 211
  • 1
  • 11
  • Thanks but my problem is I want to have an up button on action bar of app. And I want to know how to implement its click event. – Reza Abbasi Oct 10 '15 at 17:25
  • Thanks friend. But would you please to tell what should I put instead of Toast.make... to reach the parent activity? One solution is to use NavUtils.navigateUpFromSameTask(getActivity()); but my activity needs some extras to start properly. – Reza Abbasi Oct 10 '15 at 17:53