兩個建議如何做到這一點與自定義的上下文菜單。
方案A:也許這是一個選項,你只要用戶點擊G1包住當前佈局爲RelativeLayout
,並添加LinearLayout
(包含您的自定義上下文菜單)到RelativeLayout
。當單擊g2時,刪除舊的LinearLayout
並添加一個新的relativeLayout.addView(contextMenuLayout)
。爲了讓您的LinearLayout放置在底部,請確保使用contextMenuLayout.setLayoutParams(...)
並傳遞RelativeLayout.LayoutParams
的實例,並設置Align Parent Bottom和Center Horizontal。由於您的contextMenuLayout
是RelativeLayout
的最後一個元素,因此它將顯示在上面。焦點將按照你的意願行事。
備選案文B:將垂直方向的當前佈局包裝成LinearLayout
。第一個單元格包含您當前的佈局。第二個單元格可能包含您自定義的上下文菜單,您可以像變體A中那樣添加和刪除它們。兩個優點:首先,您的原始佈局未被上下文視圖覆蓋,並且這樣一切都始終可見。其次,您可以將'LinearLayout'設置爲「animateLayoutChanges」,這使得上下文菜單能夠與Android API11 +平滑地淡入淡出(在早期版本中被忽略)。
方案A和B作爲僞代碼(包括工作類似):
class YourActivity extends Activity implements OnItemClickListener {
View contextMenu = null;
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// this could be RelativeLayout (Variant A) or LinearLayout (Variant B) which in turn contains your Layout
Layout rootLayout = (Layout)findViewById(R.id.root_layout);
// in case there is a context menu open, remove it
if(contextMenu!=null)
rootLayout.removeView(contextMenu);
// add new self-defined context menu
contextMenu = getContextMenuView();
rootLayout.addView(contextMenu);
}
private View getContextMenuView() {
Layout contextMenuView = new LinearLayout(...);
.... add contents ...
return contextMenuView;
}
....
}
注意你需要投rootLayout要麼LinearLayout
或RelativeLayout
,因爲Layout
本身沒有addView(...)
方法。
謝謝你的回答,請給我更多的細節如何調用addView?比方說,我想打開onItemClick內傳遞View v作爲參數的上下文菜單。 v.addView似乎不起作用 – Don
我向答案添加了一個僞代碼。 – sulai
謝謝,我試圖在我的代碼中正確使用它。 getContextMenuView()應該是什麼,它應該返回什麼?另外是菜單佈局應該已經在root_layout或在一個單獨的XML文件?對不起,如果問題是跛腳我不是專家:) – Don