2016-02-24 1 views
0

J'ai ce code XML:bouton incorrect dans la création de l'alignement Java vs XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:id="@+id/button_bar" 
       style="?android:buttonBarStyle" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:orientation="horizontal"> 

      <Button 
       style="?android:attr/borderlessButtonStyle" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_weight="1" 
       android:layout_gravity="center" 
       android:gravity="center" 
       android:textColor="@color/md_green_400" /> 

      <Button 
       android:id="@+id/action_button" 
       style="?android:attr/borderlessButtonStyle" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:layout_weight="1" 
       android:layout_gravity="center" 
       android:gravity="center" 
       android:textColor="@color/md_green_400" /> 
    </LinearLayout> 

juste un ButtonBar d'une manière avec deux boutons sans marge. Ça marche. Cependant, je ne le veux pas, j'ai besoin de gonfler ces boutons à partir d'un JSONArray. Donc j'ai fait ceci:

for (int b = 0; b < buttons.length(); b++) { 
        final JSONObject button = buttons.getJSONObject(b); 
        LinearLayout buttonBar = (LinearLayout) child.findViewById(R.id.button_bar); 
        View buttonChild = getLayoutInflater().inflate(R.layout.flat_button, null); 
        Button action = (Button) buttonChild.findViewById(R.id.action_button); 
        action.setOnClickListener(new View.OnClickListener() { 
         @Override 
         public void onClick(View v) {} 
        }); 
        action.setText(button.getString("descricao")); 
        action.setTextColor(Color.parseColor(button.getString("text_color"))); 
        buttonBar.addView(buttonChild); 
    } 

Cela fonctionne aussi, mais les boutons obtiennent un alignement à gauche. Je veux qu'ils soient justifiés. Pourquoi ça marche quand je les laisse fixés mais pas quand je les gonfle? OBS: La "barre de boutons" est un XML juste avec un LinearLayout et le "ActionButton" est juste un XML avec un bouton.

Répondre

1

C'est la racine de votre problème:

View buttonChild = getLayoutInflater().inflate(R.layout.flat_button, null); 

Si vous ne fournissez pas la vue parent à la méthode inflate(), tous les attributs LayoutParams (par exemple layout_gravity) seront mis au rebut puisque le parent est le un pour interpréter ces attributs.

Vous pouvez corriger cela en changeant à:

View buttonChild = getLayoutInflater().inflate(
     R.layout.flat_button, buttonBar, false); 

qui lui donnera le parent vous attacher, mais pas l'attacher à la hiérarchie encore (vous le faites ci-dessous avec addView()).

+1

Parfait. Merci mec! – Notheros