Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start different activity using switch case in the menu item?

 public void onPopup(View view)
{
    final PopupMenu menu=new PopupMenu(this,view);
    menu.getMenuInflater().inflate(R.menu.menu1,menu.getMenu());


    menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
    {
        public boolean onMenuItemClick(MenuItem item)
        {

            Toast toast=Toast.makeText(MainActivity.this,
                    item.getTitle()+"Selected",Toast.LENGTH_SHORT);
            //Intent intent2 = new Intent(MainActivity.this, YourSpotActivity.class);
            //startActivity(intent2);

            //startActivity(new Intent(MainActivity.this,YourSpotActivity.class));

    toast.show();
    return true;
        }
    });
    menu.show();

}

When i click any one of the list item then it will start another activity. How can i do that by modify an above code. explain me please. I have use four car model in the menu. when i choose any one of that car then it will go to particular activity.

like image 445
Rameshbabu Avatar asked Jul 27 '13 06:07

Rameshbabu


People also ask

Does switch check all cases?

The switch statement evaluates its expression, then executes all statements that follow the matching case label. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.

What is menu bar in android?

Android ActionBar is a menu bar that runs across the top of the activity screen in android. Android ActionBar can contain menu items which become visible when the user clicks the “menu” button.

What is Action View android?

An action view is an action that provides rich functionality within the app bar. For example, a search action view allows the user to type their search text in the app bar, without having to change activities or fragments. An action provider is an action with its own customized layout.


2 Answers

You need to use switch as below

  switch (item.getItemId()) {
    case R.id.menuitem1:
    Toast.makeText(getApplicationContext(), "StartActiviy 1", Toast.LENGTH_SHORT).show();
        // start activity 1
       return true;
    case R.id.menuitem2:
    Toast.makeText(getApplicationContext(), "StartActiviy 2", Toast.LENGTH_SHORT).show();
       // start activity 2
       return true;
     default:
      //default intent
       return true;
     }

http://developer.android.com/reference/android/widget/PopupMenu.html

like image 106
Raghunandan Avatar answered Oct 15 '22 04:10

Raghunandan


You can use switch statement as below inside onMenuItemClick:

 switch (item.getItemId()) {
        case R.id.menuitem1:
            //calling intent ( activity1 )
        case R.id.menuitem2:
          //calling intent ( activity 2)
         default:
          //default intent
   }
like image 38
Butani Vijay Avatar answered Oct 15 '22 06:10

Butani Vijay