6

Androidでプログラムでビューを配置する方法を知りたいです。たとえば、この XML コードがあるとします。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:id="@+id/mainLayout">
<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="121dp"
    android:layout_marginTop="140dp"
    android:text="Results" /></RelativeLayout>

Androidでプログラムでこのレイアウトを実現するにはどうすればよいですか? テキストビューのランダムな位置が欲しいからです。

4

2 に答える 2

7

TextBox の setLayoutParams メソッドでRelativeLayout.LayoutParamsを使用する

RelativeLayout.LayoutParams p = (RelativeLayout.LayoutParams)textView1.getLayoutParams();
p.leftMargin = xxx; // in PX
p.topMargin = xxx; // in PX
textView1.setLayoutParams(p)

dp値を使用したい場合は、dpからpxへの変換を調べてください

于 2012-10-16T07:44:08.913 に答える
5

これをチェックして..

    RelativeLayout main = new RelativeLayout(this);
    main.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));



    TextView textV = new TextView(this);
        textV.setGravity(Gravity.LEFT);
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                                RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.setMargins(121, 140, 0, 0);
    textV.setLayoutParams(layoutParams);
    text.setText("Result ");

main .addView(text);
于 2012-10-16T07:52:20.177 に答える