我正在尝试根据计数器添加按钮数量。我有按钮增加计数器。问题是它显示奇数点击按钮。它甚至不会出现在点击中。例如,当我先点击时,它会显示一个按钮。我再次点击,没有按钮显示。第三次,它显示三个按钮,依此类推。谁能告诉我可能是什么问题。我发布增量代码和显示代码的按钮。
<code>
animalsEasyLayout = (LinearLayout) findViewById(R.id.animalsEasyLayout);
forward.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("mustang", "Increment");
increment();
showDigitImages();
}
});
backward.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.i("mustang", "Decrement");
decrement();
showDigitImages();
}
});
}
private void increment()
{
counter++;
digitView.setText("" + counter);
if(counter >= 10)
{
forward.setEnabled(false);
}
else
{
forward.setEnabled(true);
}
}
private void showDigitImages()
{
Log.i("mustang", "Show images for counter: " + counter);
animalsEasyLayout.removeAllViews();
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
for(int count = 0; count < counter; count++)
{
final Button b = new Button(this);
b.setId(count + 1);
b.setLayoutParams(layoutParams);
b.setText("Child: " + (++count));
animalsEasyLayout.addView(b);
}
}
private void decrement()
{
counter--;
digitView.setText("" + counter);
if(counter <= 0)
{
backward.setEnabled(false);
}
else
{
backward.setEnabled(true);
}
}
</code>
答案 0 :(得分:0)
您正在递增count
两次 - 一次在for
语句中,一次在循环中,同时拨打setText
。
for(int count = 0; count < counter; count++)
{
final Button b = new Button(this);
b.setId(count + 1);
b.setLayoutParams(layoutParams);
b.setText("Child: " + (++count));
animalsEasyLayout.addView(b);
}
使用
b.setText("Child: "+ (count + 1));