如何在Android Studio中使用Java将随机数放入按钮?先谢谢你了。
我想把随机数放4x4按钮。
我尝试了这段代码,但它在按钮中显示了数组列表:
private LinearLayout container;
int[] ran={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
container = findViewById(R.id.container);
shuffleArray(ran);
for (int i = 0; i < container.getChildCount(); i++) {
LinearLayout row = (LinearLayout) container.getChildAt(i);
for (int j = 0; j < row.getChildCount(); j++) {
Button button = (Button) row.getChildAt(j);
button.setOnClickListener(this);
button.setText(Arrays.toString(ran));
button.setTextSize(24);
}
}
}
答案 0 :(得分:1)
import java.util.*;
class IntasString{
public static void main(String args[]){
int min=1,max=15,result;
int myarr[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int range=(max-min)+1;
result=(int)(Math.random() * range) + min;
String indexValue=String.valueOf(myarr[result]);
System.out.println(indexValue);
}
}
Use this code according you and use variable indexValue to set text for Button