不知道怎样调用上下文菜单,探索中....
package com.example.testcontextmenu;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView myTextView = null;
private static final int TIME1=Menu.FIRST;
private static final int TIME2=Menu.FIRST+1;
private static final int TIME3=Menu.FIRST+2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = (TextView)findViewById(R.id.myTextView);
//注册上下文菜单
registerForContextMenu(myTextView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case TIME1:
myTextView.setBackgroundColor(Color.RED);
break;
case TIME2:
myTextView.setBackgroundColor(Color.GREEN);
break;
case TIME3:
myTextView.setBackgroundColor(Color.WHITE);
break;
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(0, TIME1, 0, "红色背景");
menu.add(0, TIME2, 0, "绿色背景");
menu.add(0, TIME3, 0, "白色背景");
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/myTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
</RelativeLayout>