menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/textSize_big"
android:title="放大"/>
<item
android:id="@+id/textSize_small"
android:title="缩小"/> </menu>
layout.xml
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" > <TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="20sp" /> </RelativeLayout>
main.java
package com.example.day10_contextview; import android.os.Bundle;
import android.app.Activity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.TextView;
import android.widget.Toast; /* contextmenu 作用在view
1.在menu文件的main.xml中编写菜单
2.在activity中创建菜单
在onCreateContextMenu方法中创建
//加载菜单布局
getMenuInflater().inflate(R.menu.main, menu);
3.和view进行绑定
将contextmenu注册到控件
registerForContextMenu(tvHello);
4.触发
长按控件会触发菜单,以对话框的形式展示,点击后自动隐藏 contextmenu和optionsmenu的点击事件都会先触发onMenuItemSelected该方法,
然后该方法再根据menu特征分发到不同的 菜单相应事件,
contextmenu触发onContextItemSelected,
optionsmenu触发onOptionsItemSelected contextmenu对比optionmenu
1.触发条件不一样,optionmenu 点击menu,contextmenu需要长按对应的控件
2.展示,optionmenu 一级菜单在底部展示,二级以对话框展示,contextmenu直接一对话框展示
3.作用点 optionmenu是相对于activity的菜单, contextmenu相对于view
*/
public class MainActivity extends Activity {
private float size ;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
//将contextMenu注册到控件上
registerForContextMenu(textView); }
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
//加载菜单布局
getMenuInflater().inflate(R.menu.main, menu); }
/**
* ContextMenu的点击事件
* 实现字体的放大缩小功能
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
size = textView.getTextSize();
switch (item.getItemId()) {
case R.id.textSize_big:
size += 5;
if(size<50){
textView.setTextSize(size);
Toast.makeText(MainActivity.this, "TextView的字体大小:"+size+"sp", 0).show();
}
break;
case R.id.textSize_small:
size -= 5;
if(size>10){
textView.setTextSize(size);
Toast.makeText(MainActivity.this, "TextView的字体大小:"+size+"sp", 0).show();
break;
}
}
return super.onContextItemSelected(item);
} }