Android 点击按钮时的条件
单击按钮时,应该会显示一些文本。这是有效的。每当超过按钮单击的限制时,它必须显示一些用户定义的文本。单击按钮3次后,它会显示一些文本,而不是用户定义的文本。以下是我的OnClickListener代码:Android 点击按钮时的条件,android,performance,android-studio,Android,Performance,Android Studio,单击按钮时,应该会显示一些文本。这是有效的。每当超过按钮单击的限制时,它必须显示一些用户定义的文本。单击按钮3次后,它会显示一些文本,而不是用户定义的文本。以下是我的OnClickListener代码: final Button btnca =(Button) findViewById(R.id.btnca); btnca.setOnClickListener(new View.OnClickListener() { @Override public void onClick(V
final Button btnca =(Button) findViewById(R.id.btnca);
btnca.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int c=1;
if(c <= 3) //if button click for first three times
{
new FancyShowCaseView.Builder(Playing.this)
.title(questionPlay.get(index).getCorrectAnswer())
.build()
.show();
score -= 10;
txtScore.setText(String.format("%d", score));
c++;
}
if(c>3) //if button click for after three times
{
new FancyShowCaseView.Builder(Playing.this)
.title("Your Limit Exceed")
.build()
.show();
}}
});
问题是c是onClick方法的局部变量,因此每次单击都从1开始。试着把它转移到班级层面
final Button btnca =(Button) findViewById(R.id.btnca);
btnca.setOnClickListener(new View.OnClickListener() {
int c=1; //initialize here so it's re-used in each onClick
@Override
public void onClick(View v) {
if(c <= 3) //if button click for first three times
{
new FancyShowCaseView.Builder(Playing.this)
.title(questionPlay.get(index).getCorrectAnswer())
.build()
.show();
score -= 10;
txtScore.setText(String.format("%d", score));
c++;
}
if(c>3) //if button click for after three times
{
new FancyShowCaseView.Builder(Playing.this)
.title("Your Limit Exceed")
.build()
.show();
}}
});
编辑:我应该提到这不是一个完整的解决方案。我将假定此代码位于Activityor Fragment.onCreate中。当重新创建生命周期组件时,计数器将在配置更改时重置,但我将把该解决方案作为练习留给读者:您应该在onClick方法之外初始化计数器变量c。当然,您应该将其初始化为c=0,而不是c=1,以便在第四次单击后获得toast 试试这个: 仅供参考,如果要重置变量c,则重置c=0,并在条件ifc>3内重置它
希望这将有助于~在setOnClickListener方法之外声明int c=1。我认为您应该将c初始化为c=0,否则在第三次单击后将获得toast。
final Button btnca =(Button) findViewById(R.id.btnca);
btnca.setOnClickListener(new View.OnClickListener() {
int c = 0;
@Override
public void onClick(View v) {
if(c <= 3) //if button click for first three times
{
new FancyShowCaseView.Builder(Playing.this)
.title(questionPlay.get(index).getCorrectAnswer())
.build()
.show();
score -= 10;
txtScore.setText(String.format("%d", score));
c++;
}
if(c>3) //if button click for after three times
{
new FancyShowCaseView.Builder(Playing.this)
.title("Your Limit Exceed")
.build()
.show();
// Reset if required
//c = 0;
}}
});