我想为我的安卓应用程序定义一个向上按钮以转到父活动。从一些资源中,我在单击向上按钮时找到了以下代码:
NavUtils.navigateUpFromSameTask(getActivity());
但是我遇到了一个问题,那就是我的活动需要一些数据来创建(Intent extras(,因此我用以下代码替换了:
getActivity().finish();
但是有些感觉告诉我,这不是达到父活动的正确方法,也许我以后会遇到一些运行时错误。你觉得我该怎么办?
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");
您还可以定义public static
变量,将其用于每个类和活动
我想你想要这个:
Intent intent = NavUtils.getParentActivityIntent(this);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this, intent);
//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);
}
更新(你想要的;-( (在创建中:
getActionBar().setDisplayHomeAsUpEnabled(true);
在主类中:
@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);
}