我试图为用户提供2个不同的视图,一个用于推荐,即(显示一个按钮),另一个用于所有信息。每次重新启动应用程序时,我都需要应用程序在所有其他按钮中调用随机按钮。
答案 0 :(得分:1)
在我看来,更好的方法是只需一个按钮,每次重启应用程序时,都会为该按钮选择随机行为。
有几种方法可以做到这一点:
public class MainActivity extends AppCompatActivity {
private static final String BUTTON_TEXT1 = "Button 1";
private static final String BUTTON_TEXT2 = "Button 2";
private static final String TEXTVIEW_TEXT1 = "Text to display #1";
private static final String TEXTVIEW_TEXT2 = "Text to display #2";
private String[] mButtonTexts = {BUTTON_TEXT1, BUTTON_TEXT2};
private String[] mTextViewTexts = {TEXTVIEW_TEXT1, TEXTVIEW_TEXT2};
private static final int NUM_OF_TEXT = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final TextView textView = (TextView) findViewById(R.id.textView);
Random random = new Random();
final int index = random.nextInt(NUM_OF_TEXT);
button.setText(mButtonTexts[index]);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
textView.setText(mTextViewTexts[index]);
}
});
}
}
答案 1 :(得分:0)
根据@MarkPazon建议
<强> 1。分配按钮(随机一个)
<强> 2。声明一个函数callRandom()
第3。从Random的Onclick事件调用函数callRandom() 按钮强>
public void callRandom(){
//Generate Random Numbers
final int min = 0;
final int max = n; //n-no of random events
Random g=new Random();
final int random = g.nextInt((max - min) + 1) + min;
//Random number 0(inclusive)-9(inclusive)
switch(random){
case 1:
//Function 1 break;
case 2:
//Function 2 break;
case 3:
//Function 3 break;
case n:
//Function n break;
}
}
PS:这里函数在每次按钮Click上调用一个Random事件。如果你希望在应用程序启动时分配随机函数,那么将它粘贴在Oncreate中
//Generate Random Numbers
final int min = 0;
final int max = n; //n-no of random events
Random g=new Random();
final int random = g.nextInt((max - min) + 1) + min;
//Random number 0(inclusive)-9(inclusive)