我正在尝试将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", . expected
。有谁知道如何解决这个问题,有没有人知道一个更好的方法来做我想做的事情?
答案 0 :(得分:0)
在setContentView调用之后添加对视图的引用
setContentView(R.layout.activity_enter_text);
view = findViewById(R.id.view1);
对于StringBuilder(String) is undefined for the type EnterText
,使用new
关键字创建一个新的StringBuilder(我认为你不需要这个)
String weight = new StringBuilder(String.valueOf(i1)).append("f").toString();
对于Syntax error on token ".0d", . expected
,只需使用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
}