/ / Posso aggiungere un layout in modo programmatico in un frammento? - android, android-frammenti

Posso aggiungere il layout in modo programmatico in un frammento? - android, android-frammenti

Nel mio frammento ho un LinearLayout, con cui voglio popolare TextViewse Buttons

Nel mio onCreate:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_checkout, container, false);
container = (LinearLayout) v.findViewById(R.id.myLayout);
return v;
}

Perché il mio contenitore è disattivato?

Sto provando questo:

for(int x = 0; x < 3; x++){
TextView text = new TextView(getActivity());
text.setText(x);
container.addView(text);
}

Ma esce. Posso farlo in fragments?

risposte:

0 per risposta № 1

Devi cambiare il codice seguente, perché stai impostando il valore intero sulla tua visualizzazione del testo.

for(int x = 0; x < 3; x++){
TextView text = new TextView(getActivity());
text.setText(String.valueOf(x));
container.addView(text);
}

0 per risposta № 2
  • Dovresti aggiungere TextView hai definito nel tuo codice. Proprio come text. tvOrder può esistere nel tuo layout.

  • E il tuo onCreteView il metodo dovrebbe tornare View .

Puoi farlo .

modificare

 <LinearLayout
android:id="@+id/myLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--you should add item here-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<LinearLayout
android:id="@+id/my_sub_linear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!--you should not add item here, and you can programatically add layout in it ?-->
</LinearLayout>

</LinearLayout>

E nel tuo codice

private LinearLayout container,mySubLinearLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_checkout, container, false);
container = (LinearLayout) v.findViewById(R.id.myLayout);
// add here
mySubLinearLayout = (LinearLayout) v.findViewById(R.id.my_sub_linear);
return v;
}

E questo codice

for(int x = 0; x < 3; x++){
TextView text = new TextView(getActivity());
text.setText(x + "");
mySubLinearLayout.addView(text);
}

Nota

Se vuoi aggiungere un layout in modo programmatico, devi impostare un layout vuoto.

Inoltre puoi rimuovere la vista completa nel tuo codice.