我在我的应用程序中需要帮助,当按下主页按钮时显示吐司,按下后退按钮并检查手机是否有导航栏
MainActivity.java
package com.example.myapp;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
Toast.makeText(getApplicationContext(), "goodbye! (home button pressed)", Toast.LENGTH_LONG).show(); //doesn't work here
finish();
return true;
}
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Toast.makeText(getApplicationContext(), "goodbye! (back button pressed)", Toast.LENGTH_LONG).show();
finish();
return true;
}
return false;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
boolean hasHomeKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_HOME);
if (hasBackKey && hasHomeKey) {
// no navigation bar
Toast.makeText(getApplicationContext(), "no nav bar", Toast.LENGTH_LONG).show();
} else {
// navigation bar
Toast.makeText(getApplicationContext(), "nav bar", Toast.LENGTH_LONG).show();
}
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@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();
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 {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
我有一个nexus 5所以它有导航栏,我认为这是问题
我该如何解决问题?
nexus 5,android 4.4.3
感谢
答案 0 :(得分:2)
框架永远不会向应用发送KEYCODE_HOME
。
现在,当用户离开您的应用时(而不是单个活动),您最好的指标就是在onTrimMemory(int)
中聆听TRIM_MEMORY_UI_HIDDEN
。
public class MainActivity extends Activity {
public void onTrimMemory(int level) {
super.onTrimMemory(level);
if (level == TRIM_MEMORY_UI_HIDDEN) {
Context ctx = getApplicationContext();
Toast.makeText(ctx, "gone", Toast.LENGTH_SHORT).show();
}
}
}
此外,您不应仅仅因为用户离开而finish()
,然后当用户返回活动时,始终必须从头开始重新创建,无需状态。