enter code here
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1;
final ImageView image;
button1 = (Button) findViewById(R.id.button1);
image = (ImageView) findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
for (int j = 1; j < 6; j++) {
int res=getResources().getIdentifier("d002_p00"+j, "drawable",getPackageName());
image.setBackgroundResource(res);
}
}
});
}
}
我有6张图片,但这段代码只显示我的第一张和最后一张图片。 它显示没有错误我该怎么办? 我怎么解决它?
答案 0 :(得分:0)
您的代码仅显示第一张和最后一张图片,因为点击监听器中的循环会遍历所有图片,而不会停止并刷新UI。如果您希望每次单击时更改图像,则应添加计数器并在每次单击时增加,而不是一次单击6次。
public class MainActivity extends Activity {
int img=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1;
final ImageView image;
button1 = (Button) findViewById(R.id.button1);
image = (ImageView) findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
img++;
img%=6;
int res=getResources().getIdentifier("d002_p00"+img, "drawable",getPackageName());
image.setBackgroundResource(res);
}
});
}
}
答案 1 :(得分:0)
将所有图片放入可绘制的文件夹中。
public class MainActivityextends Activity {
int counter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1;
final ImageView image;
counter = 0;
button1 = (Button) findViewById(R.id.button1);
image = (ImageView) findViewById(R.id.imageView1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
counter++;
counter%=6;
if(counter==0)
{
image.setBackgroundResource(R.drawable.image1);
}
else if (counter == 1)
{
image.setBackgroundResource(R.drawable.image2);
}
else if (counter == 2)
{
image.setBackgroundResource(R.drawable.image2);
}
else if (counter == 3)
{
image.setBackgroundResource(R.drawable.image2);
}
else if (counter == 4)
{
image.setBackgroundResource(R.drawable.image2);
}
else if (counter == 5)
{
image.setBackgroundResource(R.drawable.image2);
}
}
});
}
}
答案 2 :(得分:0)
像这样改变你的循环......但我没有检查它。
//Declare this in global
count=1
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(count>6)
count=1;
int res=getResources().getIdentifier("d002_p00"+count, "drawable",getPackageName());
image.setBackgroundResource(res);
count=count+1;
}
});