1.线性布局 添加按钮
注意:
1.android:orientation="vertical" 在线性布局里必须添加
2.添加程序运行java代码
package com.example.administrator.android;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.ContextMenu;import android.view.Menu;import android.view.MenuInflater;import android.view.MenuItem;import android.view.SubMenu;import android.view.View;import android.widget.Button;import android.widget.Toast;public class MainActivity extends AppCompatActivity { Button bt_1; Button bt_2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bt_1 = (Button)findViewById(R.id.bt_1); bt_2 = (Button)findViewById(R.id.bt_2); //给组件添加上下文菜单 bt_2.setOnCreateContextMenuListener(this);// //添加长按监听器// bt_2.setOnLongClickListener(new View.OnLongClickListener() {// @Override// public boolean onLongClick(View v) {// Toast.makeText(MainActivity.this, "按钮被长按", Toast.LENGTH_SHORT).show();// return true;//后面不再处理// }// }); //点击 bt_1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this, "按钮被点击", Toast.LENGTH_SHORT).show(); } }); //长按 bt_1.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { Toast.makeText(MainActivity.this, "按钮被长按", Toast.LENGTH_SHORT).show(); //事件是否已经被消费 return true; } }); } //重写创建上下文菜单的方法 @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); //代码模式(java) menu.add(1, 0, 1, "字体大小"); menu.add(1,1,2,"背景颜色"); //添加子菜单 SubMenu sm = menu.addSubMenu(1, 2, 3, "子菜单"); sm.add(2,21,0,"子菜单1"); sm.add(2,22,1,"子菜单2"); //加载文件 MenuInflater m = getMenuInflater(); m.inflate(R.menu.test3_menu,menu); } @Override public boolean onContextItemSelected(MenuItem item) { Toast.makeText(MainActivity.this, "上下文菜单的标题:"+item.getTitle(), Toast.LENGTH_SHORT).show(); return super.onContextItemSelected(item); } //给activity 添加选项菜单 //重写 @Override public boolean onCreateOptionsMenu(Menu menu) {// //添加菜单// menu.add(1,1,0,"添加");// menu.add(1,2,2,"修改");// menu.add(1,3,1,"删除"); //加载菜单文件方式 //1-获得菜单加载器 MenuInflater m = getMenuInflater(); //2-加载菜单文件 1)菜单文件 2)当前菜单 m.inflate(R.menu.test3_menu,menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Toast.makeText(MainActivity.this, "菜单项的id="+item.getItemId() +"菜单项的Title"+item.getTitle(), Toast.LENGTH_SHORT).show(); if (item.getItemId()==R.id.me_1) { Toast.makeText(MainActivity.this, "删除被执行", Toast.LENGTH_SHORT).show(); } else if (item.getItemId()==R.id.me_2) { Toast.makeText(MainActivity.this, "修改被执行", Toast.LENGTH_SHORT).show(); } return super.onOptionsItemSelected(item); }}
3。添加目录代码程序