gpt4 book ai didi

android - 在 Android 2.2 中设置按钮布局

转载 作者:行者123 更新时间:2023-11-30 04:10:58 25 4
gpt4 key购买 nike

我这里有个小问题:我想在我的计时器中制作一个按钮......但我想以随机位置放置在我的 View 中......注意:我在 Android 2.2 API 8 工作..谢谢大家!

这是我的代码:

  public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final int i=1;
Button a = (Button) findViewById(R.id.button1);
a.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CountDownTimer(20000,1000) {

@Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
//how to create a button here!
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.mainan);
Button btn = new Button(NyaActivity.this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
// i want to set position of button randomly ..
linearLayout.addView(btn);
}

@Override
public void onFinish() {
// TODO Auto-generated method stub

}
}.start();
}
});
}
}

最佳答案

Math.random()*width

其中 width 是范围的最大值,将为您提供一个随机的 x 位置,当然您也可以对高度执行相同的操作

然后你设置你的LinearLayout.LayoutParams

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(marginLeft, marginTop, 0, 0);
btn.setLayoutParams(params);

瞧,布局中的随机位置

关于android - 在 Android 2.2 中设置按钮布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com