我有一个带按钮的活动,其图像不断变化。现在单击具有特定图像的按钮时,应该给出适当的吐司。我正在使用timerTask来更改按钮图像。如何点击按钮中显示的不同图像(此处我的按钮是图像视图),我会得到不同的响应。
我的代码如下:
活动
public class MainActivity extends Activity {
public ImageView ib;
int[] images= {R.drawable.alarm,R.drawable.ic_launcher,R.drawable.music_player,R.drawable.onetouchpanel,R.drawable.recorder};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ib=(ImageView) findViewById(R.id.imageButton1);
int delay = 0; // delay for 0 sec.
int period = 2000; // repeat every 2 seconds.
Timer timer = new Timer();
MyTimerTask myTask = new MyTimerTask();
timer.schedule(myTask, delay,period);
ib.setDrawingCacheEnabled(true);
//ib.measure(Me, heightMeasureSpec)
ib.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d("ayaz","button clicked");
}
});
}
class MyTimerTask extends TimerTask {
int i=0;
public void run() {
runOnUiThread( new Runnable() {
public void run() {
// ERROR
ib.setImageResource(images[i]);
i++;
if(i>images.length-1)
{
i=0;
}
}
});
}
}
答案 0 :(得分:1)
将变量“i
”从run()
移至MainActivity
类。
还要向班级添加Button
“名称”数组:
private int i;
private final static String[] names = {"alarm", "launcher", "player", "onetouchpanel", "recorder"};
按如下方式修改代码,以在Toast
函数中显示Button.onClick()
:
ib.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final String name = names[i];
Log.d("ayaz","button clicked: #" + i + ". " + name);
Toast.makeText(MainActivity.this, "ayaz: button clicked: #" + i + ". " + name,
Toast.LENGTH_LONG).show();
}
});
答案 1 :(得分:0)
您可以将正确的文字设置为视图标记。
穿戴
ib.setTag("Text to be displayed");
在ib.setImageResource(images[i]);
之后,然后在onClick
Toast.makeText(context, (String)v.getTag(), Toast.LENGTH_SHORT).show();