In the default Android web browser, when the user clicks the 'menu' button, the menu icons slide up from the bottom and the address bar from top. How would someone implement something similar. More specifically, how would anyone add view(s) when the menu appears as a conseque开发者_运维百科nce of the user pressing the menu button?
You could override the onKeyDown
function, add your own code to an if
with the menu-button as argument, and trigger the super's onKeyDown
function afterwards (as in, always trigger that function, but only trigger your code when the key is 'menu')
You need to override the onKeyDown method:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
// Add Views here
}
return super.onKeyDown(keyCode, event);
}
If you do not want the menu to appear like normal, then return true after // Add Views here
to signify you have handled the key press.
As far as adding Views, you can use the LayoutInflater for layouts already defined in XML:
LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.someviewgroup);
// Add an inflated view directly to a ViewGroup
inflater.inflate(R.layout.whateverlayout, viewGroup);
// Or inflate a view and then add it to a ViewGroup later
View someInflatedView = inflater.inflate(R.layout.whateverlayout, null);
viewGroup.addView(someInflatedView);
Or you can create the View with code and add it:
ImageView someImageView = new ImageView(this);
someImageView.setImageDrawable(someDrawable);
someImageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
ViewGroup viewGroup = (ViewGroup) findViewById(R.id.someviewgroup);
viewGroup.addView(someImageView);
You can use onPepareOptionsMenu. It gets called just before the menu is displayed.
http://developer.android.com/reference/android/app/Activity.html#onPrepareOptionsMenu%28android.view.Menu%29
精彩评论