2012-07-14 28 views
5

En androide, que tienen un bloque de código:¿Cómo agregar el botón dinámico en otra vista?

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

En mi actividad, con RelativeLayout.LayoutParam puedo añadir el button en la posición de left, right, top, bottomroot vista, pero no puedo añadir o below etc ... de otra vista !! Entonces, ¿alguien podría sugerir agregar view que se relaciona con otro view en RelativeLayout dinámicamente?

Respuesta

7

Aquí tienes. Esto logrará lo que busca hacer:

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); 
} 
} 
+0

¡Gracias, lo intentaré! –

+0

@KingfisherPhuoc ¿puede por favor guiarme cómo puedo colocar los botones dinámicos multípticos con posición aleatoria en un diseño relativo? –

-1

Usando

Button b=new Button(this); 

usted tiene que crear nuevo botón ... y simplemente añadir una disposición en main.xml utilizando Identificación de diseño como

LinearLayout layout=(LinearLayout) findViewById(R.id.linear); 

layout.add(R.id.button); 

puede hacer esto fácilmente a agregar botón dinámicamente ..

+0

gracias, pero su sugerencia solo agrega un botón en 'LinearLayout'! Mi pregunta principal es '¿cómo agregar un botón que debe estar debajo de un EditView (o cualquier vista) en RelativeLayout dinámicamente? '! De todos modos, ¡gracias por responder! –

Cuestiones relacionadas