在TableRow上以编程方式居中TextView

时间:2013-04-25 17:08:28

标签: android textview center tablelayout tablerow

我试图将一个textview集中在一个tablerow中,它本身就在一个tablelayout中,但我想我错过了一些东西,因为TextView没有集中:s

这是我的方法:

private void insertClock() {


        TableLayout table = new TableLayout(this);
        table.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        table.setStretchAllColumns(true);

        TableRow tbRow = new TableRow(this);
        TableLayout.LayoutParams layoutRow = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);




        clock = new TextView(this);
        TableRow.LayoutParams layoutHistory = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);  


        clock.setLayoutParams(layoutHistory);
        clock.setText(calculateClockText());
        tbRow.setLayoutParams(layoutRow);
        table.addView(tbRow);
        clock.setGravity(Gravity.CENTER_HORIZONTAL);
        tbRow.addView(clock);

    }

提前致谢;)

1 个答案:

答案 0 :(得分:5)

Finnaly让它发挥作用! 这是解决方案:

private void insertClock(TableLayout table, String text) {

        TableRow tbRow = new TableRow(this);
        TableLayout.LayoutParams layoutRow = new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);


        tbRow.setLayoutParams(layoutRow);

        clock = new TextView(this);
        TableRow.LayoutParams layoutHistory = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);  
        clock.setLayoutParams(layoutHistory);
        clock.setText(text);


        clock.setGravity(Gravity.CENTER);
        tbRow.setGravity(Gravity.CENTER);
        tbRow.addView(clock);
        table.addView(tbRow);
    }