2009-12-05 20 views

risposta

110
Button myButton = new Button(this); 
myButton.setText("Push Me"); 

LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout); 
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
ll.addView(myButton, lp); 

Date un'occhiata a this esempio

+1

thnxs per ur help.Its lavoro – deepthi

+1

ho aggiornato l'URL perché quello vecchio ha dato una 404 Si prega di controllare che ho fatto riferimento alla pagina giusta. –

+0

sì è la pagina giusta, grazie – nico

8

Prova questo:

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

Button btn = new Button(this); 
btn.setText("Manual Add"); 
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); 
ll.addView(btn); 
+0

che cosa si riferisce a R.id.layout qui? Continuo a ricevere il layout come irrisolto –

+0

@AnnaGoldberg nel file XML pertinente che dovresti avere definito un LinearLayout. In questo estratto hanno dato al loro LinearLayout un id chiamato layout, in questo modo: 'android: id =" @ + id/layout "' nella loro definizione xml LinearLayout. – Amyga17

2

In realtà io aggiungo al layout file XML tutto ciò che potrebbe essere utilizzato! Quindi dal codice sorgente dell'attività specifica ottengo l'oggetto con il suo id e io "gioco" con il metodo di visibilità.

Ecco un esempio:

((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);

+1

Questo non è quello che viene chiesto. Quando le persone chiedono di aggiungere dinamicamente intendono senza un layout. Quello che stai facendo è scoprire ... non aggiungere. – Merlin

5

Prova questo codice

Button btn=new Button(this); 
btn.setId(btn); 
btn.setBackgroundResource(R.drawable.image); 
btn.setMinimumHeight(150); 
btn.setMinimumWidth(150); 
Relativelayout.addView(btn); 
+0

come posso aggiungere questo codice a una nuova attività? – Moussa

44

provare questo: codice

for (int i = 1; i <= 20; i++) { 
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.MATCH_PARENT, 
      LinearLayout.LayoutParams.WRAP_CONTENT); 
    Button btn = new Button(this); 
    btn.setId(i); 
    final int id_ = btn.getId(); 
    btn.setText("button " + id_); 
    btn.setBackgroundColor(Color.rgb(70, 80, 90)); 
    linear.addView(btn, params); 
    btn1 = ((Button) findViewById(id_)); 
    btn1.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
      Toast.makeText(view.getContext(), 
        "Button clicked index = " + id_, Toast.LENGTH_SHORT) 
        .show(); 
     } 
    }); 
} 
+5

+1 per la demo setOnClickListener. – digitaljoel

+1

perché viene aggiunto il pulsante, quindi ottenuto prima di impostare il listener dei clic. non potresti aggiungere l'ascoltatore, quindi aggiungerlo al layout ed essere fatto? – rwilson04

+0

La migliore risposta perché puoi cliccare sui pulsanti impostando un id :) – boctulus

3

Ho usato questo (o molto simile) per aggiungi diverse TextViews a un LinearLayout:

La differenza principale tra questo e il codice di dicklaw795 è che non imposta() e re-get() l'ID per ogni TextView - l'ho trovato non necessario, anche se potrebbe essere necessario per identificare successivamente ciascun pulsante in una routine di handler comune (es uno chiamato da onClick() per ogni TextView).

3

Provare il seguente codice.

LinearLayout layout = (LinearLayout) findViewById(R.id.llayout); 
layout.setOrientation(LinearLayout.VERTICAL); 

Button btn = new Button(this); 
btn.setText("Button1"); 

layout.add(btn); 

btn = new Button(this); 
btn.setText(Button2); 
layout.add(btn); 

come questo si aggiungono pulsanti secondo le vostre esigenze.

5

provare questo

private void createLayoutDynamically(int n) { 

    for (int i = 0; i < n; i++) { 
     Button myButton = new Button(this); 
     myButton.setText("Button :"+i); 
     myButton.setId(i); 
     final int id_ = myButton.getId(); 

     LinearLayout layout = (LinearLayout) findViewById(R.id.myDynamicLayout); 
     layout.addView(myButton); 

     myButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       Toast.makeText(DynamicLayout.this, 
         "Button clicked index = " + id_, Toast.LENGTH_SHORT) 
         .show(); 
      } 
     }); 
    } 
4

provare questo codice. Si lavorerà bene ..

public class DynamicViewsActivity extends Activity { 

Button button; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //setContentView(R.layout.activity_dynamic_views); 
    ScrollView scrl=new ScrollView(this); 
    final LinearLayout ll=new LinearLayout(this); 
    ll.setOrientation(LinearLayout.HORIZONTAL); 
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
    layoutParams.setMargins(100, 500, 100, 200); 
    scrl.addView(ll); 
    Button add_btn=new Button(this); 
    add_btn.setText("Click Here"); 

    ll.addView(add_btn, layoutParams); 


    final Context context = this; 

    add_btn.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 

      Intent intent = new Intent(context, App2Activity.class); 
      startActivity(intent); 
     } 
    }); 
    this.setContentView(scrl); 
} 
} 
6
for (int k = 1; k < 100; k++) { 
    TableRow row = new TableRow(this); 

    innerloop: 
    for (int l = 1; l < 4; l++) { 
     btn = new Button(this); 
     TableRow.LayoutParams tr = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     layout.setWeightSum(12.0f); 
     tr.weight = 0; 
     btn.setLayoutParams(tr); 
     btn.setTextColor(a); 
     btn.setHeight(150); 

     btn.setWidth(150); 
     btn.setId(idb); 
     btn.setText("Button " + idb); 
     row.addView(btn); 
    } 
} 
1
Button myButton = new Button(this); 
myButton.setId(123); 
myButton.setText("Push Me"); 


LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout); 
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
ll.addView(myButton, lp); 
myButton.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View view) { 
       Toast.makeText(DynamicLayout.this, 
         "Button clicked index = " + id_, Toast.LENGTH_SHORT) 
         .show(); 
      } 
     }); 
1

Se si desidera aggiungere dinamicamente i pulsanti provare questo:

public class MainActivity extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main2); 
    for (int i = 1; i <= 5; i++) { 
     LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout); 
     layout.setOrientation(LinearLayout.VERTICAL); 
     Button btn = new Button(this); 
     btn.setText(" "); 
     layout.addView(btn); 
    } 

} 
1
public void add_btn() { 

    lin_btn.setWeightSum(3f); 
    for (int j = 0; j < 3; j++) { 
     LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
       LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
     params1.setMargins(10, 0, 0, 10); 
     params1.weight = 1.0f; 

     LinearLayout ll; 
     ll = new LinearLayout(this); 
     ll.setGravity(Gravity.CENTER_VERTICAL); 
     ll.setOrientation(LinearLayout.HORIZONTAL); 
     ll.setLayoutParams(params1); 

     final Button btn; 
     btn = new Button(DynamicActivity.this); 

     btn.setText("A"+(j+1)); 
     btn.setTextSize(15); 
     btn.setId(j); 
     btn.setPadding(10, 8, 10, 10); 

     ll.addView(btn); 

     lin_btn.addView(ll); 


     btn.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       if(v.getId()==0) 
       { 
        txt_text.setText("Hii"); 
       }else if(v.getId()==1) 
       { 
        txt_text.setText("hello"); 
       }else if(v.getId()==2) 
       { 
        txt_text.setText("how r u"); 
       } 



      } 
     }); 
    } 

} 
-3

In mainactivity.xml scrittura:

<Button 
    android:id="@+id/search" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Search" 
    android:visibility="invisible"/> 

In main.java scrittura:

Button buttonSearch; 
buttonSearch = (Button)findViewById(R.id.search); 
buttonSearch.setVisibility(View.VISIBLE); 
4

controllare questo.

LinearLayout ll_Main = new LinearLayout(getActivity()); 
LinearLayout ll_Row01 = new LinearLayout(getActivity()); 
LinearLayout ll_Row02 = new LinearLayout(getActivity()); 

ll_Main.setOrientation(LinearLayout.VERTICAL); 
ll_Row01.setOrientation(LinearLayout.HORIZONTAL); 
ll_Row02.setOrientation(LinearLayout.HORIZONTAL); 

final Button button01 = new Button(getActivity()); 
final Button button02 = new Button(getActivity()); 
final Button button03 = new Button(getActivity()); 
final Button button04 = new Button(getActivity()); 

ll_Row01.addView(button01); 
ll_Row01.addView(button02); 

ll_Row02.addView(button03); 
ll_Row02.addView(button04); 

ll_Main.addView(ll_Row01); 
ll_Main.addView(ll_Row02); 

button04.setVisibility(View.INVISIBLE); 
button04.setVisibility(View.VISIBLE); 
0

si potrebbe creare un layout di base per il pulsante e dinamicamente cambiare solo ciò che è specifico, come questo progetto ho fatto per eseguire diversi esercizi da un disegno Materiale Naturalmente sto prendendo:

In questo esempio , io uso un AppCompatButton preconfigurato:

layout_base_button.xml

<android.support.v7.widget.AppCompatButton 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/btn_base" 
    android:layout_width="200dp" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:layout_marginTop="8dp" 
    style="@style/RaisedButton" 
    > 

</android.support.v7.widget.AppCompatButton> 


<style name="RaisedButton" parent="Widget.AppCompat.Button.Colored"> 
    <item name="android:textSize">11sp</item> 
    <item name="android:textStyle">bold</item> 
</style> 

E nel MainActivity ho creato alcuni casi e cambiato quello che mi serve, come il testo del pulsante e l'evento onClick:

<ScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="udemy.android.materialdesign.MainActivity"> 

    <LinearLayout 
     android:id="@+id/base_layout" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     > 

    </LinearLayout> 


</ScrollView> 



public class MainActivity extends AppCompatActivity { 


    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     LinearLayout baseLayout = findViewById(R.id.base_layout); 

     baseLayout.addView(createButton("TextFields", baseLayout, 
       view -> startActivity(createIntent(TextFieldsActivity.class)) 
     )); 

     baseLayout.addView(createButton("Buttons", baseLayout, 
       view -> startActivity(createIntent(ButtonsActivity.class)) 
     )); 

     baseLayout.addView(createButton("Toolbar", baseLayout, 
       view -> startActivity(createIntent(ToolbarActivity.class)) 
     )); 

    } 

    private View createButton(String text, LinearLayout baseLayout, View.OnClickListener onClickEvent) { 
     View inflated = LayoutInflater.from(this).inflate(R.layout.layout_base_button, baseLayout, false); 
     AppCompatButton btnBase = inflated.findViewById(R.id.btn_base); 

     btnBase.setText(text); 
     btnBase.setOnClickListener(onClickEvent); 
     return btnBase; 
    } 

    private Intent createIntent(Class<?> cls) { 
     return new Intent(this, cls); 
    } 
} 

dispiace per il ritardo ...

Problemi correlati