Android - PopupMenu 弹出式菜单

PopupMenu 可以很方便的在指定 View 下显示一个弹出菜单,而且 PopupMenu 的菜单选项可以来自于 Menu 资源。

示例代码

menu_pop.xml

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/monika" android:title="Monika" />
<item android:id="@+id/sayori" android:title="Sayori" />
<item android:id="@+id/natsuki" android:title="Natsuki" />
<item android:id="@+id/yuri" android:title="Yuri" />
<item android:id="@+id/delete" android:title="DELETE THEM ALL" />
</menu>

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<Button
android:id="@+id/btn_who"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Who?" />

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="" />

</LinearLayout>

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

final TextView tv = findViewById(R.id.textView);

findViewById(R.id.btn_who).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainActivity.this, findViewById(R.id.btn_who));
popup.getMenuInflater().inflate(R.menu.menu_pop, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@SuppressLint("SetTextI18n")
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.monika:
tv.setText("Sure, just Monika");
break;
case R.id.sayori:
case R.id.natsuki:
case R.id.yuri:
tv.setText("Oh god, you selected " + item.getTitle() + " . But you should know\nJUST MONIKA, right?");
break;
case R.id.delete:
tv.setText("Wait...What? You mean you don't need Monika anymore?");
break;
}
return true;
}
});
popup.show();
}
});
}
}

或许这有些中二

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×