感谢您提供的任何意见。我是编码新手,并设法创建一个文本播放应用程序(以随机大小和颜色显示一行文本)。我试图创建一个随机引用应用程序,并有两个按钮。我想用它们从两个单独的列表中选择一个引用。我该怎么做?我拥有的另一个按钮体验是我制作的另一个初学者应用程序,它在计数器中添加或删除了一个数字:
package com.example;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class FOREVERAPHONE extends Activity {
int counter;
Button add, sub;
TextView display;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foreveraphone);
counter = 0;
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter += 1;
display.setText("counter");
}
});
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter -= 1;
display.setText("counter");
}
});
}
}
请帮忙!我花了几个小时试图弄清楚它!非常感谢你。
答案 0 :(得分:0)
有一个名为Random的类,可用于模拟随机数的生成。
试试这个:
package com.example;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
import java.util.ArrayList<E>;
public class FOREVERAPHONE extends Activity {
int selector;
Button add, sub;
TextView display;
// List of random quotes
ArrayList<String> listOfRandomQuotes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_foreveraphone);
listOfRandomQuotes = new ArrayList<String>();
listOfRandomQuotes.add("A penny saved is a penny earned.");
listOfRandomQuotes.add("You must be the change you wish to see in the world.");
listOfRandomQuotes.add("I have decided to stick with love. Hate is too great a burden to bear.");
listOfRandomQuotes.add("By failing to prepare, you are preparing to fail.");
add = (Button) findViewById(R.id.bAdd);
sub = (Button) findViewById(R.id.bSub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random randomNumber = new Random();
selector = randomNumber.nexInt(4);
display.setText(listOfRandomQuotes.get(selector));
}
});
}
}
每次点击“添加”按钮时,都应该选择一个随机引号并显示它。
注意:请确保不要多次为视图设置OnClickListener!
希望这有帮助!