Custom TableLayout with multiple TextViews in rows

前端 未结 2 1218
[愿得一人]
[愿得一人] 2021-01-01 04:32

I want to crate custom TableLayout with rows like this:

TV is for TextView, i.e. I want to add 11 TextViews to the row:

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 05:12

    Try programmatically setting all columns to stretch (didn't seem to work in XML for me):

    ...
    flowTable.addContent(data);
    flowTable.setStretchAllColumns(true);
    

    Some other quick facts:

    • No need to try and specify height and width for TableRow within TableLayout because it will always be height=WRAP_CONTENT and width=MATCH_PARENT. See TableLayout documentation where this is listed in the Class Overview section
    • No need to try and specify height and widget for children of TableRow because they will always be height=WRAP_CONTENT and width=MATCH_PARENT. See TableRow documentation where this is listed in the Class Overview section

    Might I also humbly suggest a bit of refactoring:

    public class FlowTable extends TableLayout {
        private TableRow mCurrentRow;
    
        public FlowTable(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public FlowTable(Context context) {
            super(context);
            init();
        }
    
        private void init() {
            mCurrentRow = new TableRow(getContext());
            mCurrentRow.addView(createAndFillTextView("0")); // title for first row
            setStretchAllColumns(true);
        }
    
        public void addContent(List data) {
            for (int i = 0; i < data.size(); i++) {
                if ((i % 5 == 0) && (i != 0) /** Don't do this on 0! */) {
                    finishRowAndStartNew(i);
                }
    
                mCurrentRow.addView(createAndFillTextView(data.get(i).distance));
                mCurrentRow.addView(createAndFillTextView(data.get(i).result));
            }
        }
    
        private void finishRowAndStartNew(int newRowIndex) {
            addView(mCurrentRow);
            mCurrentRow = new TableRow(getContext());
            mCurrentRow.addView(createAndFillTextView(genRange(newRowIndex+1)));
        }
    
        private String genRange(int currIndex){
            /********************/
            return String.valueOf(currIndex);
        }
    
        private TextView createAndFillTextView(String text) {
            TextView tv = new TextView(getContext());
            tv.setText(text);        
            return tv;
        }
    }
    

提交回复
热议问题