【问题标题】:Move objects over a defined random amount in java在java中将对象移动到定义的随机量上
【发布时间】:2014-01-19 04:19:11
【问题描述】:

所以我在 android/java 中有这个 TextView,我想沿着它所在的水平轴随机定位。这是我到目前为止的代码:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <View
        android:layout_width="100dp" //This is the width I want to randomize
        android:layout_height="wrap_content"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/n5"/>

我的目标是,通过随机化android:layout_width= 行中的100dp,我可以将TextView 移动一定的随机量。有人知道怎么做吗?

谢谢!

【问题讨论】:

  • emm...您想移动定义随机数量的东西吗?看来你想做不可能的事。

标签: java android


【解决方案1】:

直接回答您的问题:
1.给视图一个id

<View android:id="@+id/picture_stream"  
      android:layout_width="100dp"  
      android:layout_height="wrap_content" />

2。在 onCreate 中以编程方式更改宽度:

...
View view_instance = (View)findViewById(R.id.nutrition_bar_filled);  
LayoutParams params=view_instance.getLayoutParams();  
params.width=newOne; //use Math.random() to create the value.
view_instance.setLayoutParams(params);

另见"view layout width - how to change programmatically"

您也可以使用边距/填充,而不是用另一个视图“推送”它。

【讨论】:

    【解决方案2】:
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    
        <TextView
            android:id="@+id/movingTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/n5"/>
    
    </LinearLayout>
    

    将 TextView 设置为水平线性布局内的唯一项,然后以编程方式为 textview 设置随机左填充。

    TextView movingTextView = (TextView) this.findViewById(R.id.movingTextView);
    movingTextView.setPaddingRelative((int) 1+Math.random()*100,0,0,0);
    

    【讨论】:

      猜你喜欢
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多