我试图在屏幕上随机显示一个TextView
,但文本不应该出现在屏幕之外。文本总是很短,不超过3个字。这是我到目前为止有:随机TextView位置
final TextView tv = ((TextView)findViewById(R.id.text);
final Random rand = new Random();
final DisplayMetrics metrics = getResources().getDisplayMetrics();
int width = rand.nextInt(metrics.widthPixels);
int height = rand.nextInt(metrics.heightPixels);
final FrameLayout.LayoutParams flp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
flp.setMargins(width, height, 0, 0);
tv.setLayoutParams(flp);
UPDATE:
忘了,我有这个功能的范围内得到一个随机数:
public static int Random(final int lower, final int uppper)
{
return lower + (int)(Math.random() * ((uppper - lower) + 1));
}
所以我的代码更新到本:
int width = Random(0, metrics.widthPixels);
int height = Random(0, metrics.heightPixels);
但它有时仍显示在查看区域之外。我甚至从每个值中减去10,以确保它保持在其中。大部分它都有,但它看起来好像显示在屏幕之外的某个地方。
其实,它帮助了一点,因为我忘了有一个功能得到一个范围内的随机数。用它更新我的OP。 –