Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android ContextMenu的使用

Android ContextMenu的使用

編輯:關於Android編程

ContextMenu介紹:

如果一個View注冊了上下文菜單,那麼當長按該View時便會彈出一個浮動菜單,來供選擇下一步操作。

\

實現這個功能需要調用setOnCreateContextMenuListener來注冊一個監聽器,那麼它和注冊長按監聽器setOnLongClickListener有什麼區別呢?下面會在代碼中加以測試,通過添加打印發現,用戶對某個View長按之後,首先觸發的是onLongClick函數,執行onLongClick操作,然後根據onLongClick的返回值判斷是不是執行OnCreateContextMenuListener函數;如果onLongClick返回false,則會繼續執行OnCreateContextMenuListener函數,如果返回true,忽略OnCreateContextMenuListener函數。

代碼如下:

public class MainActivity extends ActionBarActivity {

	ImageView mImageView ;
	MyContextMenuClickListener mContextListener;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_main);

		mImageView = (ImageView) findViewById(R.id.image);
		mContextListener = new MyContextMenuClickListener();
		mImageView.setOnCreateContextMenuListener(mContextListener);
		
		//test
		mImageView.setOnLongClickListener(new OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View arg0) {
				// TODO Auto-generated method stub
				Log.d("Test", "onLongClick");
				return false;
			}
		});
	}

	private class MyContextMenuClickListener implements OnCreateContextMenuListener , OnMenuItemClickListener{

		@Override
		public boolean onMenuItemClick(MenuItem item) {
			// TODO Auto-generated method stub
			switch(item.getItemId()){
			case R.id.open:
				Log.d("Test", "click open");
				break;
			case R.id.delete:
				Log.d("Test", "click delete");
				break;
			case R.id.remove:
				Log.d("Test", "click remove");
				break;
			default:
					break;
			}
			return true;
		}

		@Override
		public void onCreateContextMenu(ContextMenu menu, View v,
				ContextMenuInfo menuInfo) {
			// TODO Auto-generated method stub
			Log.d("Test", "onCreateContextMenu");
			
			MenuInflater inflater = getMenuInflater();
			inflater.inflate(R.menu.context_menu, menu);
			LayoutInflater layoutInflater = getLayoutInflater();
			View view = (View) layoutInflater.inflate(
					R.layout.menu_header, null);
			menu.setHeaderView(view);
			
			MenuItem open = menu.findItem(R.id.open);
			open.setOnMenuItemClickListener(mContextListener);
			MenuItem delete = menu.findItem(R.id.delete);
			delete.setOnMenuItemClickListener(mContextListener);
			MenuItem remove = menu.findItem(R.id.remove);
			remove.setOnMenuItemClickListener(mContextListener);
		}
		
	}

}

context_menu.xml


    
	    
	    
	    
	       
	    
	       
    
    

menu_header.xml



    
    


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved