我正在尝试以编程方式将 View
的布局权重设置为随机数。我认为我有正确的方法,但我无法获得一些技术细节。这是我到目前为止所拥有的:
public class EnterText extends Activity {
View view = findViewById(R.id.view1);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_text);
Random r = new Random();
int i1 = r.nextInt(5 - 1) + 1;
//This is to put the weight in a format like "1f"
String weight = new StringBuilder(String.valueOf(i1)).append("f").toString();
int height1;
view.getLayoutParams().height = height1;
int width1;
view.getLayoutParams().height = width1;
//Set the weight
view.setLayoutParams(new LayoutParams(LayoutParams.height1, LayoutParams.width1, weight));
}
}
我相信这已经接近工作了,但我遇到了一些错误。首先,我收到错误 The method StringBuilder(String) is undefined for the type EnterText
,我认为不应该发生这种情况。其次,在 0dip
处,我收到错误 Syntax error on token ".0d", 。预期
。有谁知道如何解决这个问题,有谁知道更好的方法来做我想做的事情?
最佳答案
在 setContentView 调用之后添加对 View 的引用
setContentView(R.layout.activity_enter_text);
view = findViewById(R.id.view1);
对于StringBuilder(String)对于EnterText类型未定义
,使用new
关键字来创建一个新的StringBuilder(我认为你不需要这个)
String weight = new StringBuilder(String.valueOf(i1)).append("f").toString();
对于标记“.0d”的语法错误,。预期
,只需使用 getLayoutParams().weight 并为其分配一个 float 而不是 int 值,
LinearLayout.LayoutParams lllp = (LinearLayout.LayoutParams) view.getLayoutParams();
lllp.weight = 0.25f
view.setLayoutParams(lllp); // this one may not be needed
应该看起来像:
View view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_enter_text);
view = findViewById(R.id.view1);
//Set the weight using a float n
LinearLayout.LayoutParams lllp = (LinearLayout.LayoutParams) view.getLayoutParams();
lllp.weight = 0.25f; // supply a float like this
int height1 = 200; // you have to supply a value
int width1 = 300; // you have to supply a value
lllp.width = width1;
lllp.height = height1;
view.setLayoutParams(lllp); // this one may not be needed
}
关于java - 以编程方式更改布局权重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23961472/