简体   繁体   中英

Android - how to make a TableLayout of buttons fit differently sized screens

I'm developing an Android app using fragments. In two fragments I use a TableLayout to programmatically create a matrix view consisting of buttons. The dimension of the matrix differs for different runs of the app, but typically I have 10-15 rows and 10-15 columns.

I have OddsButton extend Button.

I would like to have this view fill the screen on different devices, but I haven't been able to understand what is the right approach. I can (by hardcoding values for width and height) impact the height and width of the buttons (see below for code), but I'm struggling with fitting it to a Nexus 7 anyway. If I first find the right height to use to make it fit the screen then when I start adding more width the buttons get a bit higher as well and there is no way for me to adjust that back.

Sorry if this question is strange, but I hope that someone can make sense of this. I realize that I might be trying the totally wrong approach for this.

    for (int k=1;k<=n2;k=k+1){
        OddsButton b = new OddsButton(this.getActivity());

        b.setLeg1(no);
        b.setLeg2(k);
        b.setO(this.getO(no,k));
        b.setIndex(this.IndexForCombination(no, k));
        b.setMinimumHeight(height);
        b.setHeight(height);
        b.setMinimumWidth(width);
        b.setMinimumHeight(width);
        b.setPadding(0, 0, 0, 0);

Table Layout is a bit tricky. Please have a look at the example:

<TableLayout
    android:id="@+id/myId"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="*"
    android:weightSum="2"
    >
        <TableRow >
        <TextView 
            android:id="@+id/text1"
            android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
            android:text="bla1"
            /> 
        <TextView 
            android:id="@+id/text2"
            android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
            android:text="bla2"
            /> 
    </TableRow>
     </TableLayout

What is tricky is to first set android:stretchColumns="*" for layout (means stretch all columns) and next android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" (don't ask me why it wors like that, I will never understand some tricky things in Android, but good they work). Btw, weightSum is simply the sum of weight of elements you want to have in one row.

Sure you can have more tablerows, just the number of elements in each should be the same.

(PS please don't forget to give points if you like the answer ;)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM