简体   繁体   English

如何以编程方式为TextView甚至TableRow为基于Android的应用程序添加边距?

[英]how do i add margin programmatically for TextView or even TableRow for android-based app?

hi i've tried to add margin programmatically 嗨,我尝试过以编程方式添加保证金

i've tried using 我试过使用

TextView tv = new TextView(this);
LayoutParams params = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
params.setMargins(100, 20, 0, 0);
layout.addView(tv, params);

which uses android.widget.LinearLayout.LayoutParams, but because of the table, i got runtime error for it. 它使用android.widget.LinearLayout.LayoutParams,但是由于该表,我得到了运行时错误。

how should i do it then ? 那我该怎么办呢?

this is my code : 这是我的代码:

//create table row
TableRow trA = new TableRow(this);
        trA.setId(1000+i);
        trA.setLayoutParams(new LayoutParams (LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

        //add data to table row
        TextView tvA = new TextView (this);
        tvA.setId(2000+i);
        tvA.setText(aList.get(i).toString());
        tvA.setTextSize(18);
        tvA.setTextColor(Color.BLACK);
        tvA.setClickable(true);
        tvA.setOnClickListener(this);
        tvA.setSingleLine(false);
        tvA.setHorizontallyScrolling(false);
        tvA.setWidth(0);
        tvA.setHeight(100);

        trA.addView(tvA);
        tableA.addView(trA,new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));

== edited with import android.widget.TableLayout.LayoutParams; ==使用import android.widget.TableLayout.LayoutParams编辑; == ==

i added this at the end where i declare the tablerow 我在声明tablerow的最后添加了它

LayoutParams params = new LayoutParams (LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 0, 20);

and edited the addView at tableA 并在tableA上编辑了addView

tableA.addView(tvA, params);

i have error in the log cat, it display quite alot, so i gave the main one here : The specified child already has a parent. 我在日志猫中有错误,它显示很多,所以我在这里给出了主要的一个:指定的孩子已经有一个父母。 You must call removeView() on the child's parent first. 您必须先在孩子的父母上调用removeView()。

TableRow.LayoutParams params = new TableRow.LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
params.setMargins(100, 20, 0, 0);

You could try using TableRow.LayoutParams instead. 您可以尝试使用TableRow.LayoutParams代替。

So change your import to 因此,将导入更改为

import android.widget.TableRow.LayoutParams

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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