1
我幾乎沒有任何開發android應用程序的經驗。我的朋友問我爲他的應用程序創建一個小功能。我堅持的是爲選項創建一個子菜單,也就是說,我點擊了一個按鈕後,會彈出一個菜單並帶有一些選項,當點擊某個特定選項時我需要它打開第二個菜單。我會在下面發佈我的代碼(XML和Java),希望有人能幫助我。目前,我的菜單通過Java代碼顯示,而不是XML代碼。我不確定這是否是不好的練習,但我會讓任何能夠幫助我的人告訴我是否是這樣。提前致謝。在android中創建菜單/子菜單
XML代碼:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main"
tools:context="com.example.android.postvu.MainActivity">
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/background"
android:scaleType="centerCrop"
android:src="@drawable/grid" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:text="@string/image_text_editor"
android:textColor="@android:color/black"
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Image Text Editor" />
<Button
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
android:background="@mipmap/ic_launcher"
android:scaleType="centerCrop"
android:onClick="myOnClickMethod"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
app:layout_constraintVertical_bias="0.98" />
的Java代碼(與該按鈕被點擊,菜單顯示出來):
public void myOnClickMethod(View v) {
registerForContextMenu(v);
openContextMenu(v);
}
final int CONTEXT_MENU_VIEW = 1;
final int CONTEXT_MENU_EDIT = 2;
final int CONTEXT_MENU_ARCHIVE = 3;
@Override
public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Options");
menu.add(Menu.NONE, CONTEXT_MENU_VIEW, Menu.NONE, "Take Photo");
menu.add(Menu.NONE, CONTEXT_MENU_EDIT, Menu.NONE, "Photo Album");
menu.add(Menu.NONE, CONTEXT_MENU_ARCHIVE, Menu.NONE, "Plain Image");
}
@Override
public boolean onContextItemSelected (MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_MENU_VIEW: {
}
break;
case CONTEXT_MENU_EDIT: {
}
break;
case CONTEXT_MENU_ARCHIVE: {
}
break;
}
return super.onContextItemSelected(item);
}
https://stackoverflow.com/a/21027948/4044380是什麼? – jagapathi