ContextMenu建立及動態
ContextMenu建立及動態/ContextMenu
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.robert.sample13.MenuActivity$PlaceholderFragment"
>
<Button
android:id="@+id/menuButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Click and hold
on this button"/>
</RelativeLayout>
ContextMenu建立及動態/動態
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import
android.view.ContextMenu;
import
android.view.ContextMenu.ContextMenuInfo;
import
android.view.LayoutInflater;
import android.view.Menu;
import
android.view.MenuItem;
import android.view.View;
import
android.view.ViewGroup;
import
android.widget.Button;
import android.widget.Toast;
public class MenuActivity
extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
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.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, item.getTitle(),
Toast.LENGTH_SHORT).show();
String selectedMenu;
switch(item.getItemId()){
case R.id.menu1:
selectedMenu="menu1";
break;
case R.id.menu2:
selectedMenu="menu2";
break;
case R.id.menu3:
selectedMenu="menu3";
break;
case R.id.menu4:
selectedMenu="menu4";
break;
default:
selectedMenu="";
}
Toast.makeText(this, selectedMenu,
Toast.LENGTH_SHORT).show();
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
Toast.makeText(this, item.getTitle(),
Toast.LENGTH_SHORT).show();
return true;
}
/**
* 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_menu, container,
false);
Button
btn=(Button)rootView.findViewById(R.id.menuButton);
btn.setOnCreateContextMenuListener(PlaceholderFragment.this.getActivity());
return rootView;
}
}
}
沒有留言:
張貼留言