上下文菜单创建

发布于 2024-10-24 00:15:28 字数 42 浏览 3 评论 0原文

我做了简单的菜单。

现在我怎样才能制作一个上下文菜单?

I have made simple menu.

Now how can I make a context menu?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

走过海棠暮 2024-10-31 00:15:28

只需在 onCreate 方法中注册上下文菜单,

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView)this.findViewById(R.id.textViewId);
registerForContextMenu(this.getTextView());
}

通过添加项目在此处创建上下文菜单

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
menu.setHeaderTitle("Sample Context Menu");
menu.add(200, 200, 200, "item1");
}

,在此处响应所选项目

 @Override
public boolean onContextItemSelected(MenuItem item)
{
if (item.itemId() = some-menu-item-id)
{
//handle this menu item
return true;
}
… other exception processing
}

只需运行并获取上下文菜单:)

just register for context menu in onCreate method

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView)this.findViewById(R.id.textViewId);
registerForContextMenu(this.getTextView());
}

create ContextMenu here by adding item

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
{
menu.setHeaderTitle("Sample Context Menu");
menu.add(200, 200, 200, "item1");
}

respond here for selected item

 @Override
public boolean onContextItemSelected(MenuItem item)
{
if (item.itemId() = some-menu-item-id)
{
//handle this menu item
return true;
}
… other exception processing
}

just run and get your context menu :)

梦明 2024-10-31 00:15:28

试试这个..

     registerForContextMenu(Listview);

      @Override
   public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(Menu.NONE, 0, Menu.NONE, "Edit");
    menu.add(Menu.NONE, 1, Menu.NONE,"Delete");
    menu.add(Menu.NONE, 2, Menu.NONE,"Merge");
    //menu.add(Menu.NONE, 3, Menu.NONE,"Delete duplicate");
}

try this one..

     registerForContextMenu(Listview);

      @Override
   public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);
    menu.add(Menu.NONE, 0, Menu.NONE, "Edit");
    menu.add(Menu.NONE, 1, Menu.NONE,"Delete");
    menu.add(Menu.NONE, 2, Menu.NONE,"Merge");
    //menu.add(Menu.NONE, 3, Menu.NONE,"Delete duplicate");
}
南风起 2024-10-31 00:15:28

编辑:
抱歉,但它是相似的,您必须注册上下文菜单的视图,然后您必须 oververride 创建和选择的内容

registerForContextMenu([your view])

@Override
 public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
   switch (item.getItemId()){
        case CONTEXT_ASSIS:
            switch (item.getGroupId()){
                case CONTEXT_ASSIS:

                    break;
            }
            case R.id.navi:
                           break;
                  }

 }

 @Override
 public boolean onContextItemSelected(MenuItem item) {
     switch (item.getItemId()){
        case CONTEXT_ASSIS:
            switch (item.getGroupId()){

        case R.id.navi:

            break;
        case R.id.assis:

            break;
        case R.id.save_pos:


            break;
        case R.id.docs:

            break;

     }
     return true;
}

//ende edit

 @Override
public boolean onCreateOptionsMenu(Menu menu) {    
    MenuInflater inflater = getMenuInflater();    
    inflater.inflate(R.menu.menutest, menu);    
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {    
    // Handle item selection   
    boolean ret =super.onOptionsItemSelected(item); 
    switch (item.getItemId()) {    
        case R.id.rotate:       

            break;
        case R.id.settings:    

            break; 
        case R.id.talk:

        break;
        case R.id.calendar:

            break;
        case R.id.speechsearch:

            break;
    }
    return ret;
}

edit:
sorry, but ist's similar, you have to register the view for the contextmenü and then you have to ovverride the create and selected stuff

registerForContextMenu([your view])

@Override
 public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
   switch (item.getItemId()){
        case CONTEXT_ASSIS:
            switch (item.getGroupId()){
                case CONTEXT_ASSIS:

                    break;
            }
            case R.id.navi:
                           break;
                  }

 }

 @Override
 public boolean onContextItemSelected(MenuItem item) {
     switch (item.getItemId()){
        case CONTEXT_ASSIS:
            switch (item.getGroupId()){

        case R.id.navi:

            break;
        case R.id.assis:

            break;
        case R.id.save_pos:


            break;
        case R.id.docs:

            break;

     }
     return true;
}

//ende edit

 @Override
public boolean onCreateOptionsMenu(Menu menu) {    
    MenuInflater inflater = getMenuInflater();    
    inflater.inflate(R.menu.menutest, menu);    
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {    
    // Handle item selection   
    boolean ret =super.onOptionsItemSelected(item); 
    switch (item.getItemId()) {    
        case R.id.rotate:       

            break;
        case R.id.settings:    

            break; 
        case R.id.talk:

        break;
        case R.id.calendar:

            break;
        case R.id.speechsearch:

            break;
    }
    return ret;
}
我很坚强 2024-10-31 00:15:28

上下文菜单代码:

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout tv = (LinearLayout)findViewById(R.id.linear);
        registerForContextMenu(tv);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
        menu.setHeaderTitle("Sample Context Menu");
        menu.add("item1");
        menu.add("item2");

    }

    public boolean onContextItemSelected(MenuItem item)
    {
        if (item.getTitle().toString().equals("item1"))
        {
//handle this menu item
            Toast.makeText(this, "Hey, you selected item1", Toast.LENGTH_SHORT).show();
        }

        return true;
    }
}

Code for context Menu:

public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LinearLayout tv = (LinearLayout)findViewById(R.id.linear);
        registerForContextMenu(tv);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
    {
        menu.setHeaderTitle("Sample Context Menu");
        menu.add("item1");
        menu.add("item2");

    }

    public boolean onContextItemSelected(MenuItem item)
    {
        if (item.getTitle().toString().equals("item1"))
        {
//handle this menu item
            Toast.makeText(this, "Hey, you selected item1", Toast.LENGTH_SHORT).show();
        }

        return true;
    }
}
好倦 2024-10-31 00:15:28

我可以解释轻松制作上下文菜单的步骤:-

来自此 Github Repo 并按照以下步骤操作。

可以发现,CircleDrag类是用于拖动圆的实现。此类包含与菜单项交互的逻辑,并使用 OnViewCrossed 接口将回调返回到 MainActivity 以重绘菜单项。

检查MainActivity.java
首先我们初始化 CircleDrag 类。

私有无效 initCircleDrag(){
最终 int 半径 = (int) getResources().getDimension(R.dimen._80sdp);
最终 CircleDrag CircleDrag = new CircleDrag(this);
CircleDrag.init(viewCircle, this, radius, IndicatorViewList);}

下面的方法用于创建动态菜单项。只需传递菜单项名称和图标即可。

public void createMenuItem(String text, @DrawableRes int drawableId) {
   textViewList.add(createTextView(relativeParent, text));
   menuItemViewList.add(createMenuItem(rlCenterView, drawableId));
   indicatorViewList.add(createMenuItem(rlCenterView, R.drawable.trans_circle));

   DOTS_COUNT = textViewList.size();
}

下面的方法用于将菜单布局移动到触摸的位置。

public void setMenuItemsPosition(View parentView, View menuLayoutView, float x, float y) {

   //p for parent
   float pl, pr, pb, pt;
   //c for child
   float cl, cr, cb, ct;

   int[] v1_coords = new int[2];
   parentView.getLocationOnScreen(v1_coords);

   pl = 0;
   pr = parentView.getWidth();
   pt = 0;
   pb = parentView.getHeight();

   cl = menuLayoutView.getX();
   ct = menuLayoutView.getY();
   cr = menuLayoutView.getWidth() + cl;
   cb = menuLayoutView.getHeight() + ct;

   if (cl < pl) {
       if (ct < pt && cl < pl) {
           setMenusPosition(Angle.LEFT_TOP);
       } else if (cb > pb && cl < pl) {
           setMenusPosition(Angle.LEFT_BOTTOM);
       } else {
           setMenusPosition(Angle.LEFT);
       }
   } else if (cr > pr) {
       if (ct < pt && cr > pr) {
           setMenusPosition(Angle.RIGHT_TOP);
       } else if (cb > pb && cr > pr) {
           setMenusPosition(Angle.RIGHT_BOTTOM);
       } else {
           setMenusPosition(Angle.RIGHT);
       }
   } else if (ct < pt) {
       setMenusPosition(Angle.TOP);
   } else if (cb > pb) {
       setMenusPosition(Angle.BOTTOM);
   } else {
       setMenusPosition(Angle.CENTER);
   }

}

下面的方法用于根据角度绘制菜单项圆。如果用户触摸中心菜单项,则菜单项绘制为圆形;如果用户触摸侧面,则菜单项绘制为半圆;如果用户触摸屏幕的任意角度,则菜单项绘制为圆的四分之一。

private void setMenusPosition(Angle angle);

下面的监听器用于在长按时显示上下文菜单视图。

relativeParent.setOnLongClickListener(new View.OnLongClickListener() {
   @Override
   public boolean onLongClick(View v) {
       return false;
   }
});

final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
   public void onLongPress(MotionEvent e) {
       Log.e("GestureDetector", "Longpress detected");

       if (setVisible) {
           rlMenuView.setVisibility(View.VISIBLE);
           rlTouchLayout.setBackgroundResource(R.color.menu_background);
           isLongPressDetected = true;
       }

   }
});

下面的侦听器用于检测触摸并在触摸点周围绘制菜单项。

relativeParent.setOnTouchListener(new View.OnTouchListener() {

   @Override
   public boolean onTouch(View v, MotionEvent event) {

       if (event.getX() >= getResources().getDimension(R.dimen._10sdp) && event.getX() <= relativeParent.getWidth() - getResources().getDimension(R.dimen._10sdp) &&
               event.getY() >= getResources().getDimension(R.dimen._10sdp) && event.getY() <= relativeParent.getHeight() - getResources().getDimension(R.dimen._10sdp)) {
           setVisible = true;
           //pass touch event

           viewCircle.dispatchTouchEvent(event);

           switch (event.getAction()) {

               case MotionEvent.ACTION_DOWN:

                   lastSelectedPosition = -1;

                   float centerX = event.getX() - rlMenuView.getWidth() / 2;
                   float centerY = event.getY() - rlMenuView.getHeight() / 2;

                   rlMenuView.setX(centerX);
                   rlMenuView.setY(centerY);

                   setMenuItemsPosition(relativeParent, rlMenuView, centerX, centerY);

                   break;
               case MotionEvent.ACTION_MOVE:

                   break;

               case MotionEvent.ACTION_UP:

                   if (lastSelectedPosition != -1) {
                       onMenuSelected(lastSelectedPosition, textViewList.get(lastSelectedPosition).getText().toString());
                   } else {
                       onNoMenuSelected();
                   }

                   setVisible = false;
                   setMenusPosition(Angle.CENTER);
                   rlMenuView.setVisibility(View.INVISIBLE);
                   rlTouchLayout.setBackgroundResource(R.color.tranparent);
                   hideTextViews();

                   break;
           }

       } else {

           if (event.getAction() == MotionEvent.ACTION_UP) {

               onNoMenuSelected();

               setVisible = false;
               setMenusPosition(Angle.CENTER);
               rlMenuView.setVisibility(View.INVISIBLE);
               rlTouchLayout.setBackgroundResource(R.color.tranparent);
               hideTextViews();
           }

       }

       return false;
   }

});

下面的方法用于在选择或未选择项目时重绘菜单项和菜单文本。

@Override
public void OnViewTouched(int flag) {
   Log.d(TAG, "onSelect: ");

   lastSelectedPosition = -1;

   for (int i = 0; i < DOTS_COUNT; i++) {

       if (flag == indicatorViewList.get(i).getId()) {
           lastSelectedPosition = i;

           if ((int) pos_center_view[0] > (int) indicatorViewList.get(i).getX()
                   && (pos_center_view[0] - indicatorViewList.get(i).getX() > 4)) {
               menuItemViewList.get(i).setX(indicatorViewList.get(i).getX() - getResources().getDimension(R.dimen._6sdp));
           } else if ((int) pos_center_view[0] < (int) indicatorViewList.get(i).getX()
                   && (indicatorViewList.get(i).getX() - pos_center_view[0] > 4)) {
               menuItemViewList.get(i).setX(indicatorViewList.get(i).getX() + getResources().getDimension(R.dimen._6sdp));
           } else {
               menuItemViewList.get(i).setX(indicatorViewList.get(i).getX());
           }

           if ((int) pos_center_view[1] > (int) indicatorViewList.get(i).getY()
                   && (pos_center_view[1] - indicatorViewList.get(i).getY() > 4)) {
               menuItemViewList.get(i).setY(indicatorViewList.get(i).getY() - getResources().getDimension(R.dimen._6sdp));
           } else if ((int) pos_center_view[1] < (int) indicatorViewList.get(i).getY()
                   && (indicatorViewList.get(i).getY() - pos_center_view[1] > 4)) {
               menuItemViewList.get(i).setY(indicatorViewList.get(i).getY() + getResources().getDimension(R.dimen._6sdp));
           } else {
               menuItemViewList.get(i).setY(indicatorViewList.get(i).getY());
           }

           textViewList.get(i).setVisibility(View.VISIBLE);

       } else {
           menuItemViewList.get(i).setX(indicatorViewList.get(i).getX());
           menuItemViewList.get(i).setY(indicatorViewList.get(i).getY());

           textViewList.get(i).setVisibility(View.INVISIBLE);
       }
   }

}

当选择菜单项或未选择任何内容时,将调用以下方法。

@Override
public void onMenuSelected(int position, String selectedText) {
   tvResult.setText(String.format("Selected Item : %s", selectedText));
}

@Override
public void onNoMenuSelected() {
   // TODO when no menu selected.....
   tvResult.setText(String.format("Selected Item : %s", "None"));
}

这是此完整演示的 GitHub 链接

I can explain steps to make context menu easily :-

First clone demo project from this Github Repo and follow below steps.

You can find, CircleDrag class is used for dragging circle implementation. This class contains logic for interaction with menu items and return callback to MainActivity using OnViewCrossed interface to redraw menu items.

Check MainActivity.java
First we initialize CircleDrag class.

private void initCircleDrag(){
final int radius = (int) getResources().getDimension(R.dimen._80sdp);
final CircleDrag circleDrag = new CircleDrag(this);
circleDrag.init(viewCircle, this, radius, indicatorViewList);}

Below method is used to create dynamic menu items. Just pass menu item name and icon.

public void createMenuItem(String text, @DrawableRes int drawableId) {
   textViewList.add(createTextView(relativeParent, text));
   menuItemViewList.add(createMenuItem(rlCenterView, drawableId));
   indicatorViewList.add(createMenuItem(rlCenterView, R.drawable.trans_circle));

   DOTS_COUNT = textViewList.size();
}

Below method is used to move menu layout to touched position.

public void setMenuItemsPosition(View parentView, View menuLayoutView, float x, float y) {

   //p for parent
   float pl, pr, pb, pt;
   //c for child
   float cl, cr, cb, ct;

   int[] v1_coords = new int[2];
   parentView.getLocationOnScreen(v1_coords);

   pl = 0;
   pr = parentView.getWidth();
   pt = 0;
   pb = parentView.getHeight();

   cl = menuLayoutView.getX();
   ct = menuLayoutView.getY();
   cr = menuLayoutView.getWidth() + cl;
   cb = menuLayoutView.getHeight() + ct;

   if (cl < pl) {
       if (ct < pt && cl < pl) {
           setMenusPosition(Angle.LEFT_TOP);
       } else if (cb > pb && cl < pl) {
           setMenusPosition(Angle.LEFT_BOTTOM);
       } else {
           setMenusPosition(Angle.LEFT);
       }
   } else if (cr > pr) {
       if (ct < pt && cr > pr) {
           setMenusPosition(Angle.RIGHT_TOP);
       } else if (cb > pb && cr > pr) {
           setMenusPosition(Angle.RIGHT_BOTTOM);
       } else {
           setMenusPosition(Angle.RIGHT);
       }
   } else if (ct < pt) {
       setMenusPosition(Angle.TOP);
   } else if (cb > pb) {
       setMenusPosition(Angle.BOTTOM);
   } else {
       setMenusPosition(Angle.CENTER);
   }

}

Below method is used to draw menu items circle based on the angle. If user touch in center menu items draws in round shape, if user touch on sides then menu items draw in half of the circle and if user touch on any angle of the screen then menu items draw in fourth of the circle.

private void setMenusPosition(Angle angle);

Below listener is used to show contextual menu view when long press is performed.

relativeParent.setOnLongClickListener(new View.OnLongClickListener() {
   @Override
   public boolean onLongClick(View v) {
       return false;
   }
});

final GestureDetector gestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
   public void onLongPress(MotionEvent e) {
       Log.e("GestureDetector", "Longpress detected");

       if (setVisible) {
           rlMenuView.setVisibility(View.VISIBLE);
           rlTouchLayout.setBackgroundResource(R.color.menu_background);
           isLongPressDetected = true;
       }

   }
});

Below listener is used to detect touch and draw menu items around touched point.

relativeParent.setOnTouchListener(new View.OnTouchListener() {

   @Override
   public boolean onTouch(View v, MotionEvent event) {

       if (event.getX() >= getResources().getDimension(R.dimen._10sdp) && event.getX() <= relativeParent.getWidth() - getResources().getDimension(R.dimen._10sdp) &&
               event.getY() >= getResources().getDimension(R.dimen._10sdp) && event.getY() <= relativeParent.getHeight() - getResources().getDimension(R.dimen._10sdp)) {
           setVisible = true;
           //pass touch event

           viewCircle.dispatchTouchEvent(event);

           switch (event.getAction()) {

               case MotionEvent.ACTION_DOWN:

                   lastSelectedPosition = -1;

                   float centerX = event.getX() - rlMenuView.getWidth() / 2;
                   float centerY = event.getY() - rlMenuView.getHeight() / 2;

                   rlMenuView.setX(centerX);
                   rlMenuView.setY(centerY);

                   setMenuItemsPosition(relativeParent, rlMenuView, centerX, centerY);

                   break;
               case MotionEvent.ACTION_MOVE:

                   break;

               case MotionEvent.ACTION_UP:

                   if (lastSelectedPosition != -1) {
                       onMenuSelected(lastSelectedPosition, textViewList.get(lastSelectedPosition).getText().toString());
                   } else {
                       onNoMenuSelected();
                   }

                   setVisible = false;
                   setMenusPosition(Angle.CENTER);
                   rlMenuView.setVisibility(View.INVISIBLE);
                   rlTouchLayout.setBackgroundResource(R.color.tranparent);
                   hideTextViews();

                   break;
           }

       } else {

           if (event.getAction() == MotionEvent.ACTION_UP) {

               onNoMenuSelected();

               setVisible = false;
               setMenusPosition(Angle.CENTER);
               rlMenuView.setVisibility(View.INVISIBLE);
               rlTouchLayout.setBackgroundResource(R.color.tranparent);
               hideTextViews();
           }

       }

       return false;
   }

});

Below method is used to redraw menu items and menu text when item is selected or not selected.

@Override
public void OnViewTouched(int flag) {
   Log.d(TAG, "onSelect: ");

   lastSelectedPosition = -1;

   for (int i = 0; i < DOTS_COUNT; i++) {

       if (flag == indicatorViewList.get(i).getId()) {
           lastSelectedPosition = i;

           if ((int) pos_center_view[0] > (int) indicatorViewList.get(i).getX()
                   && (pos_center_view[0] - indicatorViewList.get(i).getX() > 4)) {
               menuItemViewList.get(i).setX(indicatorViewList.get(i).getX() - getResources().getDimension(R.dimen._6sdp));
           } else if ((int) pos_center_view[0] < (int) indicatorViewList.get(i).getX()
                   && (indicatorViewList.get(i).getX() - pos_center_view[0] > 4)) {
               menuItemViewList.get(i).setX(indicatorViewList.get(i).getX() + getResources().getDimension(R.dimen._6sdp));
           } else {
               menuItemViewList.get(i).setX(indicatorViewList.get(i).getX());
           }

           if ((int) pos_center_view[1] > (int) indicatorViewList.get(i).getY()
                   && (pos_center_view[1] - indicatorViewList.get(i).getY() > 4)) {
               menuItemViewList.get(i).setY(indicatorViewList.get(i).getY() - getResources().getDimension(R.dimen._6sdp));
           } else if ((int) pos_center_view[1] < (int) indicatorViewList.get(i).getY()
                   && (indicatorViewList.get(i).getY() - pos_center_view[1] > 4)) {
               menuItemViewList.get(i).setY(indicatorViewList.get(i).getY() + getResources().getDimension(R.dimen._6sdp));
           } else {
               menuItemViewList.get(i).setY(indicatorViewList.get(i).getY());
           }

           textViewList.get(i).setVisibility(View.VISIBLE);

       } else {
           menuItemViewList.get(i).setX(indicatorViewList.get(i).getX());
           menuItemViewList.get(i).setY(indicatorViewList.get(i).getY());

           textViewList.get(i).setVisibility(View.INVISIBLE);
       }
   }

}

Below methods are called when menu item is selected or nothing is selected.

@Override
public void onMenuSelected(int position, String selectedText) {
   tvResult.setText(String.format("Selected Item : %s", selectedText));
}

@Override
public void onNoMenuSelected() {
   // TODO when no menu selected.....
   tvResult.setText(String.format("Selected Item : %s", "None"));
}

Here is GitHub Link for this complete demo.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文