[英]Change layout weight programmatically
我試圖以編程方式將 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
, The method StringBuilder(String) is undefined for the type EnterText
,我認為這不應該發生。 其次,在0dip
,我收到Syntax error on token ".0d", . expected
的錯誤Syntax error on token ".0d", . expected
Syntax error on token ".0d", . expected
。 有人知道如何解決這個問題,有人知道做我想做的更好的方法嗎?
在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
Syntax error on token ".0d", . expected
,只需使用getLayoutParams()。weight並為其分配浮點數而不是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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.