0

So I have this TextView in android/java that I would like to position randomly along the horizontal axis where it is located. This is the code I have so far:

<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"/>

My goal is that, by randomizing the 100dp in the android:layout_width= line, I can move my TextView over by a certain random amount. Would anyone know how to do this?

Thanks!

  • emm... you want to move something a *defined*, *random* amount? seems you're wanting to do the impossible. – hd1 Jan 18 '14 at 19:12

2 Answers2

0

To answer your question directly:
1. give the View an id

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

2. change width programmatically in 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);

See also "view layout width - how to change programmatically".

You could also use margin/padding instead of "pushing" it with another view.

Community
  • 1
  • 1
Chrisport
  • 2,936
  • 3
  • 15
  • 19
0
<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>

Set the TextView as the sole item inside a horizontal Linear Layout and then programatically set a random left padding for the textview.

TextView movingTextView = (TextView) this.findViewById(R.id.movingTextView);
movingTextView.setPaddingRelative((int) 1+Math.random()*100,0,0,0);
W.K.S
  • 9,787
  • 15
  • 75
  • 122