如何随机化字符串? 我有 3个字符串和 1 TextView 。对于TextViev,我想"写"字符串,当单击按钮时。 我的代码是:
主要xml:
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="100dp"
android:text="Push Me"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView1"
tools:ignore="UnknownId" />
<TextView
android:id="@+id/tv1"
android:text="VALAMI"
android:layout_width="0dp"
android:layout_height="182dp"
android:layout_marginBottom="18dp"
android:layout_marginEnd="6dp"
android:layout_marginStart="6dp"
android:layout_marginTop="163dp"
app:layout_constraintBottom_toTopOf="@+id/button1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="UnknownId" />
MainActivity.java
Button btn1;
TextView tv1;
String a = "s1";
String b = "s2";
String c = "s3";
答案 0 :(得分:0)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> strings = {"s1", "s2", "s3"};
Button button = findViewById(R.id.btn1);
TextView text = findViewById(R.id.tv1);
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Random randomno = new Random();
text.setText(strings.get(randomno.nextInt(3));
}
});
}