Lesson 15. Context menu
Android Lessons

Lesson 15. Context menu


In this lesson we:

– create a context menu

The context menu is called on Android by long press on any screen component. Usually it is used in lists when a list of homogeneous objects (such as letters in mail) is displayed and to perform an action on one of these objects we call the context menu for it. But because we have not yet passed the lists, we will make the example easier and call the context menu for TextView.

Let’s create a project:

Project name: P0151_ContextMenu
Build Target: Android 2.3.3
Application name: ContextMenu
Package name: ru.startandroid.develop.contextmenu
Create Activity: MainActivity

Open main.xml and draw two TextViews there:



    
    
    
    

For the first TextView, we will create a context menu that will change the color of the text. For the second, we will resize the text.

The principle of creating a context menu is similar to creating a regular menu. But there are also differences.

The onCreateContextMenu creation method is called each time before the menu is displayed. At the entrance he is sent:

ContextMenuTo which we will add items
View – the screen element for which the context menu is called
ContextMenu.ContextMenuInfo – contains Add Information when a context menu is called for a list item. While we are not using it, but when we look at the lists, we will find that the thing is useful.

The onContextItemSelected processing method is similar to the method onOptionsItemSelected for the regular menu. The input is transmitted MenuItem – the menu item that was clicked.

We will also need the third registerForContextMenu method. To the entrance it is transferred View which means that you need to create a context menu for this View. If you do not follow this method, the context menu for View will not be created.

Let’s code it, let’s open it MainActivity.java. We describe and find TextView and let’s say that you need to create a context menu for them.

  TextView tvColor, tvSize;
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tvColor = (TextView) findViewById(R.id.tvColor);
        tvSize = (TextView) findViewById(R.id.tvSize);
        
        // для tvColor и tvSize необходимо создавать контекстное меню
        registerForContextMenu(tvColor);
        registerForContextMenu(tvSize);
            
    }

Now let’s describe the creation of context menus. We use constants to store the IDs of menu items.

  final int MENU_COLOR_RED = 1;
  final int MENU_COLOR_GREEN = 2;
  final int MENU_COLOR_BLUE = 3;
  
  final int MENU_SIZE_22 = 4;
  final int MENU_SIZE_26 = 5;
  final int MENU_SIZE_30 = 6;

And we create

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
        ContextMenuInfo menuInfo) {
      // TODO Auto-generated method stub
      switch (v.getId()) {
    case R.id.tvColor:
      menu.add(0, MENU_COLOR_RED, 0, "Red");
      menu.add(0, MENU_COLOR_GREEN, 0, "Green");
      menu.add(0, MENU_COLOR_BLUE, 0, "Blue");
      break;
    case R.id.tvSize:
      menu.add(0, MENU_SIZE_22, 0, "22");
      menu.add(0, MENU_SIZE_26, 0, "26");
      menu.add(0, MENU_SIZE_30, 0, "30");
      break;
    }
    }

Note that we are on ID we define ViewFor which it was summoned context menu and depending on that we create a specific menu. That is, if the context menu is called for tvColor, Then we create a menu listing the colors, And if for tvSize with font sizes.

We used constants as the ID of the points. We do not use grouping and sorting, so we use zeros as appropriate parameters.

You can save and run everything. Pressing TextView for a long time should bring up context menus.

But clicking on them gives us nothing because we did not register the processing in the onContextItemSelected method. Let’s spell out:

    @Override
    public boolean onContextItemSelected(MenuItem item) {
      // TODO Auto-generated method stub
      switch (item.getItemId()) {
      // пункты меню для tvColor
    case MENU_COLOR_RED:
      tvColor.setTextColor(Color.RED);
      tvColor.setText("Text color = red");
      break;
    case MENU_COLOR_GREEN:
      tvColor.setTextColor(Color.GREEN);
      tvColor.setText("Text color = green");
      break;
    case MENU_COLOR_BLUE:
      tvColor.setTextColor(Color.BLUE);
      tvColor.setText("Text color = blue");
      break;
    // пункты меню для tvSize
    case MENU_SIZE_22:
      tvSize.setTextSize(22);
      tvSize.setText("Text size = 22");
      break;
    case MENU_SIZE_26:
      tvSize.setTextSize(26);
      tvSize.setText("Text size = 26");
      break;
    case MENU_SIZE_30:
      tvSize.setTextSize(30);
      tvSize.setText("Text size = 30");
      break;
      }
      return super.onContextItemSelected(item);
    }

In this method we define by IDWhich menu item was clicked. And do the following: change the text color for tvColor or font size for tvSize. We store, run and verify that context menus now respond to clicks and do what is required of them.

To broaden my horizons, I would like to write some more on this topic. It may seem difficult, so if suddenly it is not clear, nothing is wrong. So, thoughts aloud.

We used the registerForContextMenu (View view) method to include a context menu for a particular View. This method belongs to the Activity class. I looked at the weekend of this method, it says the following:

  public void registerForContextMenu(View view) {
    view.setOnCreateContextMenuListener(this);
  }

We mention our handler lesson and look at the setOnCreateContextMenuListener method (View.OnCreateContextMenuListener l). It turns out that View uses the object as the context menu creation handler this. In this case, this code is in Activity, So this is Activity and is. That is, when View wants show context menu, It appeals to handler (Activity), and he is already implementing his method onCreateContextMenu. That is the same principle as when you click.

And the line in MainActivity.java:

registerForContextMenu(tvColor);

is absolutely equivalent to this line:

tvColor.setOnCreateContextMenuListener(this);

Generally, we can create our own object that implements the View.OnCreateContextMenuListener interface and use it instead of Activity as a context menu creation handler.

Remember, you can also use the XML method for the context menu, which was discussed at the end of last lesson. Try to do the same lesson, but already using the XML menu.

Full lesson code:

public class MainActivity extends Activity {

  final int MENU_COLOR_RED = 1;
  final int MENU_COLOR_GREEN = 2;
  final int MENU_COLOR_BLUE = 3;

  final int MENU_SIZE_22 = 4;
  final int MENU_SIZE_26 = 5;
  final int MENU_SIZE_30 = 6;

  TextView tvColor, tvSize;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tvColor = (TextView) findViewById(R.id.tvColor);
    tvSize = (TextView) findViewById(R.id.tvSize);

    // для tvColor и tvSize необходимо создавать контекстное меню
    registerForContextMenu(tvColor);
    registerForContextMenu(tvSize);
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.tvColor:
      menu.add(0, MENU_COLOR_RED, 0, "Red");
      menu.add(0, MENU_COLOR_GREEN, 0, "Green");
      menu.add(0, MENU_COLOR_BLUE, 0, "Blue");
      break;
    case R.id.tvSize:
      menu.add(0, MENU_SIZE_22, 0, "22");
      menu.add(0, MENU_SIZE_26, 0, "26");
      menu.add(0, MENU_SIZE_30, 0, "30");
      break;
    }
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) {
    // пункты меню для tvColor
    case MENU_COLOR_RED:
      tvColor.setTextColor(Color.RED);
      tvColor.setText("Text color = red");
      break;
    case MENU_COLOR_GREEN:
      tvColor.setTextColor(Color.GREEN);
      tvColor.setText("Text color = green");
      break;
    case MENU_COLOR_BLUE:
      tvColor.setTextColor(Color.BLUE);
      tvColor.setText("Text color = blue");
      break;
    // пункты меню для tvSize
    case MENU_SIZE_22:
      tvSize.setTextSize(22);
      tvSize.setText("Text size = 22");
      break;
    case MENU_SIZE_26:
      tvSize.setTextSize(26);
      tvSize.setText("Text size = 26");
      break;
    case MENU_SIZE_30:
      tvSize.setTextSize(30);
      tvSize.setText("Text size = 30");
      break;
    }
    return super.onContextItemSelected(item);
  }
}

In the next lesson:

– we draw the screen programmatically, not through the layout file




Discuss in the forum [171 replies]

Leave a Reply

Your email address will not be published. Required fields are marked *