I have a Service
which is executed once in every 5 minute.It shows an AlertDialog
when executed.I want to start a Fragment
on AlertDialog
button click.I tried to start the Fragment
like
android.app.FragmentManager fm = ((Activity) getApplicationContext()).getFragmentManager();
but gives exception java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
.
This is my code for AlertDialog
:
Handler mHandler = new Handler(getMainLooper());
mHandler.post(new Runnable() {
@Override
public void run() {
final AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext(),R.style.Theme_AppCompat_Light_Dialog_Alert)
.create();
// Setting Dialog Title
alertDialog.setTitle(eventNameEnglish);
// Setting Dialog Message
alertDialog.setMessage(eventAddressEnglish+"\n"+duration);
// Setting View Details Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,"View Details", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
android.app.FragmentManager fm = ((Activity) getApplicationContext()).getFragmentManager();
dialog_fragment = new DetailFragment("Events",
eventNameEnglish, eventAddressEnglish,
eventContactNumberEnglish, eventEmailEnglish, eventFaxEnglish,
duration,eventOrganizerNameEnglish,
eventDescriptionEnglish,eventFullDescriptionEnglish,
eventLocationEnglish,eventImageEnglish,
eventWebsiteEnglish
);
dialog_fragment.show(fm, "detailScreen");
}
});
// Setting Cancel Button
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,"Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
// Showing Alert Message
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
});
How to do this?Please help.
答案 0 :(得分:3)
The exception tells the problem. getApplicationContext return value cannot cast to Activity. You have to taget an existing activity.
I think you need some communication between the service and the activity.
You can use Eventbus or broadcastreceiver or something like that.
http://developer.android.com/reference/android/content/BroadcastReceiver.html
答案 1 :(得分:1)
You cannot show a Fragment
alone, A Fragment
can only display UI embedded within an Activity
. So, you question is a bit to broad to be answered properly.
However, here are a couple of pointers:
activity_layout
with a frame_layout
as placeholder for your fragmentActivity
with activity_layout
as contentIntent
onCreate
method of your Activity
, you can get a FragmentManager
and then show your fragment.答案 2 :(得分:0)
you can start activity , then only you can show the fragment from that. This is because without activity , getFragmentManager() will return null