5

アンドロイドでは、私はコードのブロックを持っています:

// RelativeLayout with id is "root": main.xml
<EditText 
    android:id="@+id/pref_edit_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:hint="Text to share in preference"
/>
// This is the button I want to add to main.xml
 <Button 
    android:id="@+id/save_button"
    android:layout_below="@id/pref_edit_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Save"
/>

私の活動では、ビューの位置にをRelativeLayout.LayoutParam追加することはできますが、別のビューの追加などはできません!! だから、誰もが動的に別のものに関連するを追加するための提案を与えることができますか?buttonleft, right, top, bottomrootbelowviewviewRelativeLayout

4

1 に答える 1

7

どうぞ。これにより、あなたが探していることを達成できます。

public class ExampleActivity extends Activity {
private RelativeLayout rl;
private EditText editText;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_example);

    rl = (RelativeLayout) findViewById(R.id.main_rl);
    editText = (EditText) findViewById(R.id.pref_edit_text);

    Button button = new Button(this);
    button.setText("Save");

    // create the layout params that will be used to define how your
    // button will be displayed
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

    // add the rule that places your button below your EditText object
    params.addRule(RelativeLayout.BELOW, editText.getId());

    // set the layoutParams on the button
    button.setLayoutParams(params);

    // add button to your RelativeLayout
    rl.addView(button);
}
}
于 2012-07-14T05:59:46.770 に答える