我试图在屏幕上随机显示一个TextView
,但文字不应该出现在屏幕之外。文字总是很短,不超过3个字。这是我到目前为止:
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);
更新:
忘了,我有这个函数来获取一个范围内的随机数:
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,以确保它保持不变。大部分都是这样,但它似乎显示在屏幕外的某个地方。
尝试查找更多关于让随机数保持在最大宽度和高度内,
但它有时仍会显示在观看区域之外