安卓常用View(视图开发技巧总结)
程序员文章站
2022-03-23 08:00:09
本篇常用的View如图中所示:xml布局代码
本篇常用的View如图中所示:
xml布局代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn_menu_contextMenu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="显示ContentMenu"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="1.点击menu显示选项菜单\n2.长按按钮显示上下文菜单"
android:textSize="25sp"/>
</LinearLayout>
menu-xml代码
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="添加2"
android:id="@+id/add">
</item>
<item android:title="删除2"
android:id="@+id/delete">
</item>
</menu>
java代码
public class MenuActivity extends AppCompatActivity {
private Button btn_menu_contextMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
Button btn_menu_contextMenu = findViewById(R.id.btn_menu_contextMenu);
btn_menu_contextMenu.setOnCreateContextMenuListener(this);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(0, 4, 0, "添加");
menu.add(0, 5, 0, "删除");
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 4:
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
}
return super.onContextItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// menu.add(0, 2, 0, "添加");
// menu.add(0, 3, 0, "删除");
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.option_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 2:
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.add:
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
case R.id.delete:
Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
}
总结:
OptionMenu
1. 如何触发Menu的显示?
点击menu键
2. 如何向Menu中添加MenuItem?
重写onCreateOptionMenu()
menu.add()或者加载菜单文件
3. 选择某个MenuItem时如何响应?
重写onOptionsItemSelected(), 根据itemId做响应
ContextMenu
1. 如何触发Menu的显示?
长按某个视图
view.setOnCreateContextMenuListener(this)
2. 如何向Menu中添加MenuItem?
重写onCreateContextMenu()
menu.add()
3. 选择某个MenuItem时如何响应?
重写onContextItemSelected(), 根据itemId做响应
本文地址:https://blog.csdn.net/we1less/article/details/107733441
上一篇: springboot解决跨域请求带cookie的问题
下一篇: 美图,干吃不胖,羡煞旁人的靓女图片