如何在Android中动态设置布局参数? [英] How to dynamically set layout parameters in Android?

查看:192
本文介绍了如何在Android中动态设置布局参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些我动态生成的文本字段。但我似乎无法为他们设置布局参数。请告诉我我在做错什么。



我可以生成没有布局参数的字段。但是,如果我使用 LayoutParams ,它甚至不会生成。



代码:

  TableLayout table =(TableLayout)findViewById .id.TableLayout1); 

TableRow tr = new TableRow(this);
LinearLayout.LayoutParams trparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(trparams);

cg [i] = new EditText(this);
weight [i] = new EditText(this);
cg [i] .setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
weight [i] .setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

//这里出错了。通过添加fieldparams,文本字段甚至不生成。
LinearLayout.LayoutParams fieldparams = new LinearLayout.LayoutParams(10,LinearLayout.LayoutParams.WRAP_CONTENT,1.0f);
tr.addView(cg [i],fieldparams);
tr.addView(weight [i],fieldparams);

table.addView(tr);


解决方案

您正在将表行添加到表中,因此使用 TableLayout.LayoutParams 而不是 LinearLayout.LayoutParams 。因为我们使用LayoutParam根据我们要添加的父项


I have these text fields which I generated dynamically. But I can't seem to set layout parameters for them. Please tell me what I'm doing wrong.

I'm able to generate the fields without layout parameters. However, If I use LayoutParams, it doesn't even get generated.

Code:

TableLayout table = (TableLayout) findViewById(R.id.TableLayout1);

TableRow tr = new TableRow(this);
LinearLayout.LayoutParams trparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(trparams);

cg[i] = new EditText(this);
weight[i] = new EditText(this);
cg[i].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
weight[i].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);

//Here's where it goes wrong. By adding fieldparams, the text field doesn't even get generated.
LinearLayout.LayoutParams fieldparams = new LinearLayout.LayoutParams(10, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);
tr.addView(cg[i], fieldparams);
tr.addView(weight[i], fieldparams);

table.addView(tr);

解决方案

You are adding Table Row into table so use TableLayout.LayoutParams instead of LinearLayout.LayoutParams.As we use LayoutParam according to parent in which we are going to add

这篇关于如何在Android中动态设置布局参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆