随机TextView位置

问题描述 投票:4回答:3

我试图在屏幕上随机显示一个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,以确保它保持不变。大部分都是这样,但它似乎显示在屏幕外的某个地方。

android android-layout random textview
3个回答
0
投票

尝试查找更多关于让随机数保持在最大宽度和高度内,


0
投票

为什么你不能这样做?

您可以找到设备的Max x和Max y,然后根据条件将View的位置设置为特定位置,而不是这样做。

另见:SO

可能对你有所帮助。

评论我的任何查询。


0
投票

但它有时仍会显示在观看区域之外

  1. 你的活动没有头衔吗?这确实有点......我不确定,但我认为通知栏也是如此......如果你在全屏模式下工作,你就不应该有问题。
  2. 请记住,x y坐标始终是对象视图的左上角!所以你的图片/文本视图/屏幕之外的任何内容都会得到一半(或完整的情况:D)仍然可能发生...
© www.soinside.com 2019 - 2024. All rights reserved.