从微调器中选择项目后如何在单击按钮时显示结果

时间:2019-06-11 16:05:27

标签: android android-layout

我已经编写了掷骰子的代码。当用户单击1个骰子时,它应该给出1到6之间的数字。当用户单击2个骰子时,它应该生成2到12之间的数字。我使用了微调器和图像按钮。但是我不知道将逻辑放置在哪里骰子1和骰子2生成该范围内的数字。

public class MainActivity extends AppCompatActivity implements 

AdapterView.OnItemSelectedListener {


private ImageButton  btnroll;
private Spinner spinner;
private static final String[] paths = {"1 dice", " 2 dice"}

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    spinner = (Spinner)findViewById(R.id.spinner);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_spinner_item,paths);

  adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(this);
    btnroll= findViewById(R.id.btnRoll);

}
     public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
   switch (position) {
        case 0:


        case 1:


        case 2:


    }
}

我知道显示图像按钮结果的代码是这样的,但是不知道如何将它与微调器连接起来。示例的onclick按钮代码仅适用于骰子1。请帮助

   btnroll.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
    Random rand = new Random();
    int result = rand.nextInt( (1 - 6) + 1) + 1;
    final int random = new Random().nextInt((max - min) + 1) + min;
  Toast.makeText(getApplicationContext(),String.valueOf(result),Toast.LENGTH_LONG).show();


}
     })

2 个答案:

答案 0 :(得分:0)

尝试将btnroll中的结果变量声明为类变量。这样,您可以访问外部值。希望对您有所帮助。

答案 1 :(得分:0)

int max, min;
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
    switch (position) {
       case 0:
            break;
       case 1:
            min = 1;
            max = 6;
            break;
       case 2:
            min = 2;
            max = 12;
            break;
      }
}

或者如果不需要在外部使用最大/最小,

btnroll.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        int index = spinner.getSelectedItemPosition();
        if (index == 0) {
            return;
        }
        int min = index * 1;
        int max = index * 6;
        Random rand = new Random();
        final int random = new Random().nextInt((max - min) + 1) + min;
        Toast.makeText(getApplicationContext(),String.valueOf(result),Toast.LENGTH_LONG).show();
    }
});