Question:
Hello everyone! I'm trying to launch an activity in a separate thread with a time interval, the code is this: And the question itself: everything works, the activity starts, is it possible to do it as a separate method or how, so that in each case I don’t write new Handler().postDelayed(new Runnable() {
arr_imageA[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
v.startAnimation(anim);
mediaPlayer.start();
playSample(R.raw.click_sound);
switch (v.getId())
{
case R.id.imageView1:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(getActivity(), a1.class));
}
}, 100);
break;
case R.id.imageView2://todo копипаст
startActivity(new Intent(getActivity(), a2.class));
break;
case R.id.imageView3:
startActivity(new Intent(getActivity(), a3.class));
break;
}
}
});
Answer:
method
public void startActivity(final Context activityContext, final Class<? extends Activity> activityClass) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(activityContext, activityClass));
}
}, 100);
}
In your code, the only difference is that you launch different activities, so you need to take out this part (different activities) as a parameter for the method. Looking at the constructor declaration for the Intent class
public Intent(Context packageContext, Class<?> cls)
we see that the second parameter is Class<?> cls
, where <?>
means any data type (i.e. Class from any data type). Next, we take this parameter into our own method and make it like this Class<? extends Activity> activityClass
where <? extends Activity>
means we want to accept Class from any data type whose parent is Activity
Well, then in the case we pass specific instances of the Сlass of the corresponding activities
startActivity(getActivity(), a1.class); //и так далле
since the parent of any activity is Context, the above method call is valid