简体   繁体   English

如何使一个按钮执行一项任务,该任务取决于Java android中单击了哪个先前的按钮?

[英]How to make one button do a task that depends on which previous buttons has been clicked in Java android?

I am trying to make a simple math training app with levels , the plan is to make the user press on the button of the level he wants then the Go button will appear when he press Go the app starts and it generates random numbers based on the difficulty of the level he chose, now how to make the Go button play the app according to the level has been pressed , this is what i have tried so far but for some reason the app just crashes . 我正在尝试制作一个带有级别的简单数学训练应用程序,该计划是让用户按下他想要的级别的按钮,然后当他按下Go时将出现“ Go”按钮。该应用程序启动,并根据他选择的级别的难度,现在如何按级别使Go按钮播放应用程序,这是我到目前为止尝试过的,但是由于某种原因,应用程序崩溃了。 ps this isn't the full code just the related issue of the code " ps这不是完整的代码,而只是相关的代码问题“

public void levelsWay(View view){

if (view.getTag().toString().equals("L1")) {
    a = rano.nextInt(21);
    b = rano.nextInt(51);
}

else if (view.getTag().toString().equals("L2")){
    a = rano.nextInt(101);
    b = rano.nextInt(151);
}
else if (view.getTag().toString().equals("L3")){
    a = rano.nextInt(151);
    b = rano.nextInt(501);
}
else if (view.getTag().toString().equals("L4")){
    a = rano.nextInt(501);
    b = rano.nextInt(1001);

}

} }

public void generateQuestions() { 公共无效的generateQuestions(){

    levelsWay(null);

    c=rano.nextInt(4);
 switch (c) {
     case 0:op='+';
         break;
     case 1:op='-';
         break;
     case 2:op='*';
         break;
     case 3:op='/';
         break;
         default:op='?';
 }
    sumtextview.setText(Integer.toString(a) + op + Integer.toString(b));

} }

public void start(View view) {
    starts.setVisibility(View.INVISIBLE);
    Gamelayout.setVisibility(View.VISIBLE);
    playAgain(findViewById(R.id.pp));


}

You need to set the tag inside your xml layout file where the buttons are stated and then inside your code you getTag from the view and use it accordingly something as follows 您需要在声明了按钮的xml布局文件中设置标签,然后在代码中从视图中获取getTag并相应地使用它,如下所示

Set tag for each button as follows 如下设置每个按钮的标签

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btn_level_1"
    android:tag="L1" // Setting tag here />

Then inside the onClick listener do the following 然后在onClick侦听器中执行以下操作

btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        String level = view.getTag().toString();
        Log.d(TAG, "Level Selected : " + level);
        // Apply the rest of the logic
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM