【发布时间】:2021-09-14 08:20:44
【问题描述】:
我试图让一个按钮出现在屏幕上的随机位置,但由于某种原因它一直熄灭。我试图玩弄这些价值观,但似乎并没有解决问题。我对此进行了很多搜索,甚至尝试关注this,但没有成功。我在Activity的onCreate方法中使用下面的代码块来实现它。
setContentView(R.layout.button_press);
button = findViewById(R.id.my_button);
button.setClickable(true);
button.setOnClickListener(this);
final Button button = (Button) findViewById(R.id.my_button);
displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
loOPenArea = (RelativeLayout) findViewById(R.id.open_area_press);
int leftMargin = new Random().nextInt(displaymetrics.widthPixels - 5*button.getWidth());
int topMargin = new Random().nextInt(displaymetrics.heightPixels - 5*button.getHeight());
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) button.getLayoutParams();
p.setMargins(leftMargin, topMargin, 0, 0);
button.setLayoutParams(p);
这是布局的代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ButtonPress"
android:background="#03B0F5"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/open_area_press">
<TextView
android:id="@+id/button_press"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:background="#FFFFFF"
android:text="@string/button_press"
android:textSize="50sp"
android:textColor="#03B0F5"
/>
<androidx.appcompat.widget.AppCompatButton
android:id = "@+id/my_button"
android:layout_width = "150dp"
android:layout_below="@+id/button_press"
android:height="150dp"
android:layout_height = "wrap_content"
android:background="@drawable/rounded_corners"
android:text = "Press Here"
android:textColor="#03B0F5"
android:textSize="20sp"
/>
</RelativeLayout>
</LinearLayout>
有时按钮根本不显示在屏幕上,或者它在某个地方被挤压(见右下角):
让按钮出现在随机屏幕位置似乎是一项微不足道的任务,但我已经尝试解决了几天并寻找解决方案,但似乎没有一个解决方案能完美运行。
【问题讨论】:
标签: android android-layout button random position