开发者

Android LayoutWidth being disregarded by cascaded use of LayoutInflater

I am building a pyramid of buttons and want the size of the pyramid to be able to change dynamically. To accomplish this, I have extremely basic XML files representing the activity, each row of the activity, and each button. I am modeling the solution from the accepted response to this question. The pyramid constructs correctly, but the 50dip button width is not being adhered to. Any ideas why? Is there a better way of doing this?

main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pyramid" 
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center_horizontal"
/>

row.xml:

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/row"  
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center_horizontal"/>

btn.xml:

<?xml version="1.0" encoding="utf-8"?>
    <Button xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/button" 
        android:layout_width="50dip" 
        android:layout_height="wrap_content"/>

Main Activity:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    i开发者_开发问答nflate();
    }
private void inflate() {
    LinearLayout pyramidLayout = (LinearLayout) findViewById(R.id.pyramid);

    for (int row = 1 ; row <= mSize; ++row) {
        View rowView = getLayoutInflater().inflate(R.layout.row, null);
        LinearLayout rowLayout = (LinearLayout) rowView.findViewById(R.id.row);
        for (int column = 1; column <= row; ++column) {
            View btnView = getLayoutInflater().inflate(R.layout.btn, null);
            Button btn = (Button) btnView.findViewById(R.id.button);
            btn.setId(row*10 + column);
            rowLayout.addView(btnView);
        }
        pyramidLayout.addView(rowView); 
    }
}


In btn.xml, change layout_width="50dip" to width="50dip".


Thanks you for this tutorial. It really helps me :) In my case, I have a view (2 texts, 1 image, 1 button) who represents 1 result. When the user click on "search" I need to display it many time. So your example was perferct for me

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜