android使用代码动态做表格

本文介绍了一个使用Android原生API动态生成表格布局的方法,通过代码创建TableLayout和TableRow,并设置显示分隔线,实现灵活的表格布局效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

动态生成表格布局
package com.anyikang.emergency120.aek.activity;

import android.annotation.SuppressLint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.anyikang.emergency120.aek.R;

public class RescueOrderNotifyActivity extends AppCompatActivity {

    LinearLayout layoutPush;
    private Drawable drawable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TableLayout tableLayout = new TableLayout(this);
         drawable = this.getResources().getDrawable(R.drawable.table_border);
        tableLayout.setDividerDrawable(drawable);
        tableLayout.setShowDividers(TableLayout.SHOW_DIVIDER_BEGINNING|TableLayout.SHOW_DIVIDER_END|TableLayout.SHOW_DIVIDER_MIDDLE);
        tableLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.WRAP_CONTENT));

        for(int i = 0; i < 3; i++)
        {
            TableRow tableRow = new TableRow(this);
            tableRow.setOrientation(LinearLayout.HORIZONTAL);
            tableRow.setDividerDrawable(drawable);
            tableRow.setShowDividers(TableLayout.SHOW_DIVIDER_BEGINNING|TableLayout.SHOW_DIVIDER_END|TableLayout.SHOW_DIVIDER_MIDDLE);

            TextView textView = new TextView(this);
            TextView textView2 = new TextView(this);
            textView.setText("标题"+i);
            textView2.setText("标题"+(i+1));
            textView.setLayoutParams(new TableRow.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT,1));
            textView2.setLayoutParams(new TableRow.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT,1));


            tableRow.addView(textView);
            tableRow.addView(textView2);
            tableLayout.addView(tableRow);
        }
        setContentView(tableLayout);


    }
}

在drawable文件夹下创建XML shape资源文件:table_border

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="1dp"
        android:height="1dp" />

    <solid android:color="@color/main_bg" />

</shape>

其中的color自己定义吧,在此不再贴出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冉航--小虾米

希望得到您的鼓励和交流

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值