首先,我是android开发的新手。
今天在我们的应用程序中,我们有一个选择颜色的按钮。单击红色按钮,将显示一个巨大的对话框,您可以在其中选择一种颜色。
我想改成这样:
颜色不仅是图标,而且是在画布上以编程方式绘制的圆圈。
所以我的问题是,我如何拥有一个比常规菜单/菜单项更高级的弹出菜单。我应该从哪里开始寻找?可以使用片段吗?
答案 0 :(得分:1)
您可以将任何视图包括到PopupWindow元素中。根据您的情况,我可以推荐此解决方案。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
popupButtonView.setOnClickListener {
val linearLayout = LinearLayout(applicationContext)
linearLayout.orientation = LinearLayout.VERTICAL
linearLayout.setBackgroundColor(Color.LTGRAY)
for (i in 0..5) {
linearLayout.addView(createTextView("Your text $i"))
}
PopupWindow(
linearLayout,
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
).showAsDropDown(popupButtonView)
//Use this line, if you want change gravity
//.showAtLocation(popupButtonView, Gravity.TOP, 0, 0)
}
}
private fun createTextView(tvText: String): TextView = TextView(applicationContext).apply {
gravity = Gravity.CENTER_VERTICAL
text = tvText
compoundDrawablePadding = DRAWABLE_PADDING
setPadding(TEXT_VIEW_PADDING)
setCompoundDrawablesWithIntrinsicBounds(getCircleShape(), null, null, null)
}
private fun getCircleShape(): ShapeDrawable = ShapeDrawable(OvalShape()).apply {
paint.color = getRandomColor()
intrinsicHeight = SHAPE_SIZE
intrinsicWidth = SHAPE_SIZE
}
private fun getRandomColor(): Int = Color.argb(255, Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))
companion object {
const val TEXT_VIEW_PADDING = 20
const val DRAWABLE_PADDING = 20
const val SHAPE_SIZE = 50
}
}
答案 1 :(得分:0)
可能您需要的是PopupMenu:
public void showPopup(View v) {
PopupMenu popup = new PopupMenu(this, v);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.menu_example, popup.getMenu());
popup.show();
}
弹出菜单的布局:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/mail"
android:icon="@drawable/ic_mail"
android:title="@string/mail" />
<item android:id="@+id/upload"
android:icon="@drawable/ic_upload"
android:title="@string/upload"
android:showAsAction="ifRoom" />
<item android:id="@+id/share"
android:icon="@drawable/ic_share"
android:title="@string/share" />
</menu>