下面列出了怎么用android.support.v4.app.DialogFragment的API类实例代码及写法,或者点击链接到github查看源代码。
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
setStyle( DialogFragment.STYLE_NORMAL, R.style.TimelineCommentsDialog );
final Context c = getActivity();
final View dialogView = LayoutInflater.from(c).inflate(R.layout.dialog_wholikes, null);
likesNumber = Integer.valueOf(getArguments().getString(LIKES));
id=getArguments().getLong(POSTID);
lv = (ListView) dialogView.findViewById(R.id.TimeLineListView);
final TextView likes = (TextView) dialogView.findViewById(R.id.likes);
if(likesNumber == 1) {
likes.setText(likesNumber + " " + getString(R.string.timeline_like));
}else{
likes.setText(likesNumber + " " + getString(R.string.likes));
}
return new AlertDialog.Builder(c)
.setView(dialogView)
.create();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments().getInt("num");
// Pick a style based on the num.
int style = DialogFragment.STYLE_NORMAL, theme = 0;
switch ((mNum-1)%6) {
case 1: style = DialogFragment.STYLE_NO_TITLE; break;
case 2: style = DialogFragment.STYLE_NO_FRAME; break;
case 3: style = DialogFragment.STYLE_NO_INPUT; break;
case 4: style = DialogFragment.STYLE_NORMAL; break;
case 5: style = DialogFragment.STYLE_NO_TITLE; break;
case 6: style = DialogFragment.STYLE_NO_FRAME; break;
case 7: style = DialogFragment.STYLE_NORMAL; break;
}
switch ((mNum-1)%6) {
case 2: theme = android.R.style.Theme_Panel; break;
case 4: theme = android.R.style.Theme; break;
case 5: theme = android.R.style.Theme_Light; break;
case 6: theme = android.R.style.Theme_Light_Panel; break;
case 7: theme = android.R.style.Theme_Light; break;
}
setStyle(style, theme);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTheme = mPresenter.getTheme();
switch (mTheme) {
case Constants.ThemeType.Blue:
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.AlertDialogStyle_Blue);
break;
case Constants.ThemeType.Gray:
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.AlertDialogStyle_Gray);
break;
case Constants.ThemeType.Dark:
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.AlertDialogStyle_Dark);
mDarkThemeJS = getDarkThemeJS();
break;
default:
setStyle(DialogFragment.STYLE_NO_TITLE, R.style.AlertDialogStyle_Base);
break;
}
}
@Override
public void onClick(int payType, String imsi, String price, String currency) {
DialogFragment df = new ProgressDialogFragment();
df.setCancelable(false);
df.show(getSupportFragmentManager(), "pleaseWaitDialog");
PayProductRequestUnitel requestUnitel = new PayProductRequestUnitel();
requestUnitel.setProductId(String.valueOf(aptoideProductId));
requestUnitel.setPayType(String.valueOf(payType));
requestUnitel.setToken(token);
requestUnitel.setImsi(imsi);
requestUnitel.setPrice(price);
requestUnitel.setCurrency(currency);
requestUnitel.setRepo(repo);
requestsetExtra(requestUnitel);
requestUnitel.setRetryPolicy(noRetryPolicy);
spiceManager.execute(requestUnitel, new PurchaseRequestListener());
}
@Override
public void onDisplayPreferenceDialog(Preference preference) {
if (callback != null) {
callback.onSettingChanged();
}
DialogFragment dialogFragment = null;
if (preference instanceof StylePreference) {
dialogFragment
= StylePreferenceDialogFragment
.newInstance(preference);
} else if (preference instanceof ColumnCountPreference) {
dialogFragment
= ColumnCountPreferenceDialogFragment
.newInstance(preference);
}
if (dialogFragment != null) {
dialogFragment.setTargetFragment(this, 0);
dialogFragment.show(this.getFragmentManager(), DIALOG_FRAGMENT_TAG);
return;
}
super.onDisplayPreferenceDialog(preference);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final ProgressDialog dialog = new ProgressDialog(getActivity());
//
Bundle b = getArguments();
if (b != null) {
String title = b.getString("title");
String content = b.getString("content");
dialog.setTitle(title);
dialog.setMessage(content);
}
//dialog.setCanceledOnTouchOutside(true);
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setIndeterminate(true);
//dialog.setCancelable(true);
// etc...
this.setStyle(DialogFragment.STYLE_NO_FRAME, android.R.style.Theme);
return dialog;
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if (volleyError.networkResponse != null) {
// Save request status code
requestStatusCode = volleyError.networkResponse.statusCode;
if (BuildConfig.DEBUG)
Timber.e("%s URL: %s. ERROR: %s", this.getClass().getSimpleName(), requestUrl, new String(volleyError.networkResponse.data));
// If AccessToken expired. Logout user and redirect to home page.
if (getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN && fragmentManager != null) {
LoginDialogFragment.logoutUser();
DialogFragment loginExpiredDialogFragment = new LoginExpiredDialogFragment();
loginExpiredDialogFragment.show(fragmentManager, LoginExpiredDialogFragment.class.getSimpleName());
}
} else {
requestStatusCode = CONST.MissingStatusCode;
}
return super.parseNetworkError(volleyError);
}
@Override
public void onPassphraseOKClick(DialogFragment dialog, String passphrase, boolean savePassphrase, String type) {
LOGGER.debug("Key passphrase entered.");
if (savePassphrase) {
LOGGER.debug("Saving passphrase..");
currentDevice.setKeyfilePass(passphrase);
currentDevice.setModifiedAt(new Date());
new Thread() {
@Override
public void run() {
deviceDb.update(currentDevice);
}
}.start();
}
// dirty hack: type is commandId
Long commandId = Long.parseLong(type);
LOGGER.debug("Starting command dialog for command id " + commandId);
openCommandDialog(commandId, passphrase);
}
public void testCallback() throws Throwable {
final WritableMap options = new WritableNativeMap();
options.putDouble("date", getDateInMillis(2020, 5, 6));
final DialogFragment datePickerFragment = showDialog(options);
runTestOnUiThread(
new Runnable() {
@Override
public void run() {
((DatePickerDialog) datePickerFragment.getDialog())
.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
}
});
getInstrumentation().waitForIdleSync();
waitForBridgeAndUIIdle();
assertEquals(0, mRecordingModule.getErrors());
assertEquals(1, mRecordingModule.getDates().size());
assertEquals(2020, (int) mRecordingModule.getDates().get(0)[0]);
assertEquals(5, (int) mRecordingModule.getDates().get(0)[1]);
assertEquals(6, (int) mRecordingModule.getDates().get(0)[2]);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_dialog_or_activity);
if (savedInstanceState == null) {
// First-time init; create fragment to embed in activity.
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
DialogFragment newFragment = MyDialogFragment.newInstance();
ft.add(R.id.embedded, newFragment);
ft.commit();
}
// Watch for button clicks.
Button button = (Button)findViewById(R.id.show_dialog);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
}
/**
* Get immersion bar.
*
* @param fragment the fragment
* @param isOnly the is only
* @return the immersion bar
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public ImmersionBar get(android.app.Fragment fragment, boolean isOnly) {
checkNotNull(fragment, "fragment is null");
checkNotNull(fragment.getActivity(), "fragment.getActivity() is null");
if (fragment instanceof android.app.DialogFragment) {
checkNotNull(((android.app.DialogFragment) fragment).getDialog(), "fragment.getDialog() is null");
}
String tag = mTag;
if (isOnly) {
tag += fragment.getClass().getName();
} else {
tag += System.identityHashCode(fragment);
}
return getFragment(fragment.getChildFragmentManager(), tag).get(fragment);
}
private void showTimePickerFragment(int action) {
DialogFragment newFragment = null;
switch (action){
case PickTimeFragment.ACTION_JUMP_TO_TIME:
newFragment = JumpToTimeDialog.newInstance(mTheme);
break;
case PickTimeFragment.ACTION_SLEEP_TIMER:
newFragment = SleepTimerDialog.newInstance(mTheme);
break;
default:
return;
}
if (newFragment != null)
newFragment.show(getActivity().getSupportFragmentManager(), "time");
dismiss();
}
@Override
public void onLongClickDialogSelection(Photoset photoset, int which) {
Log.d(TAG, "onLongClickDialogSelection()");
FragmentTransaction ft =
mActivity.getSupportFragmentManager().beginTransaction();
ft.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
if (photoset != null) {
Fragment prev = mActivity.getSupportFragmentManager()
.findFragmentByTag(AddToPhotosetDialogFragment.TAG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
DialogFragment newFragment =
AddToPhotosetDialogFragment.newInstance(photoset);
newFragment.show(ft, AddToPhotosetDialogFragment.TAG);
} else {
Log.e(TAG, "onLongClickDialogSelection: photoset is null");
}
}
private static void showDialog(@NonNull AppCompatActivity activity,
@NonNull DialogFragment fragment,
@NonNull String tag) {
Check.getInstance().isInMainThread();
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(tag);
if (prev != null) ft.remove(prev);
ft.addToBackStack(null);
fragment.show(ft, tag);
}
@Override
public void onManualEntryClick(int callbackId) {
dismissPickCardSourceDialogFragment();
Set<Class<? extends CardData>> cardDataClasses = new HashSet<>();
for (Class<? extends CardData> cardDataClass : CardData.getCardDataClasses()) {
if (cardDataClass.getAnnotation(CardData.Metadata.class).editDialogFragmentClass()
!= DialogFragment.class) {
cardDataClasses.add(cardDataClass);
}
}
PickCardDataClassDialogFragment.create(cardDataClasses, -1).show(
getSupportFragmentManager(), PICK_CARD_DATA_CLASS_DIALOG_FRAGMENT_TAG);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("ReplaceAllFragment", "onCreate");
if (savedInstanceState != null && fileET != null) {
// files = savedInstanceState.getString("Files");
// saveTo = savedInstanceState.getString("SaveTo");
fileET.setText(savedInstanceState.getString("Files"));
saveToET.setText(savedInstanceState.getString("SaveTo"));
includeET.setText(savedInstanceState.getString("include"));
excludeET.setText(savedInstanceState.getString("exclude"));
stardictET.setText(savedInstanceState.getString("stardict"));
isRegexCB.setChecked(savedInstanceState.getBoolean("isRegex", false));
caseSensitiveCB.setChecked(savedInstanceState.getBoolean("caseSensitive", false));
includeEnterCB.setChecked(savedInstanceState.getBoolean("includeEnter", false));
backupCB.setChecked(savedInstanceState.getBoolean("backup", false));
statusTV.setText(savedInstanceState.getString("statusTV"));
}
if (this.getShowsDialog()) {
setStyle(DialogFragment.STYLE_NO_TITLE, 0);
} else {
setHasOptionsMenu(true);
}
}
@Override
public void onMissedClick(View v) {
super.onMissedClick(v);
AlertDialog alert;
if (v.equals(measuredFGView)) {
alert = alertBuilder.editTextFloatAlert(measuredFGViewText, measuredFGViewTitle).create();
}
else if (v.equals(measuredOGView)) {
alert = alertBuilder.editTextFloatAlert(measuredOGViewText, measuredOGViewTitle).create();
}
else if (v.equals(measuredBatchSizeView)) {
alert = alertBuilder.editTextFloatAlert(measuredBatchSizeViewText,
measuredBatchSizeViewTitle).create();
}
else if (v.equals(brewDateView)) {
// Show the brew date picker and return.
DialogFragment newFragment = new DatePickerFragment();
Bundle args = new Bundle();
newFragment.setArguments(args);
newFragment.show(this.getSupportFragmentManager(), "datePicker");
return;
}
else {
Log.d("EditRecipeActivity", "onMissedClick did not handle the clicked view");
return; // In case its none of those views...
}
// Force keyboard open and show popup
alert.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
alert.show();
}
@Override
public void onDisplayPreferenceDialog(Preference preference) {
if (preference instanceof ShaderListPreference) {
DialogFragment f = ShaderListPreferenceDialogFragment
.newInstance(preference.getKey());
f.setTargetFragment(this, 0);
f.show(getFragmentManager(),
"ShaderListPreferenceDialogFragment");
return;
}
super.onDisplayPreferenceDialog(preference);
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setRetainInstance(true);
mDaysArray = getResources().getStringArray(R.array.days_array);
unpackBundle();
if (!mIsCustomDaysArraySpecified)
mDayIndex--;
mCalendar = Calendar.getInstance();
mCalendar.set(Calendar.HOUR_OF_DAY, mHour);
mCalendar.set(Calendar.MINUTE, mMinute);
switch (mTheme)
{
case SlideDayTimePicker.HOLO_DARK:
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Dialog_NoActionBar);
break;
case SlideDayTimePicker.HOLO_LIGHT:
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
break;
default: // if no theme was specified, default to holo light
setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
}
}
public static void showChangelog(FragmentManager fm) {
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(TAG);
if (prev != null) {
ft.remove(prev);
}
try {
DialogFragment dialog = ChangelogFragment.newInstance();
dialog.show(ft, TAG);
} catch (IllegalArgumentException | IllegalStateException ignored) {}
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("API123", "onCreate");
boolean setFullScreen = false;
if (getArguments() != null) {
setFullScreen = getArguments().getBoolean("fullScreen");
}
if (setFullScreen)
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
}
public static DialogFragment newInstance(String key) {
ColorPickerDialogPreference colorPickerDialogPreference = new ColorPickerDialogPreference();
Bundle b = new Bundle(1);
b.putString("key", key);
colorPickerDialogPreference.setArguments(b);
return colorPickerDialogPreference;
}
@Override
public void onDisplayPreferenceDialog(Preference preference) {
if (preference instanceof ChameleonMiniSlotPickerPreference) {
DialogFragment dialogFragment =
new ChameleonMiniSlotPickerPreference.NumberPickerFragment();
final Bundle b = new Bundle();
b.putString("key", preference.getKey());
dialogFragment.setArguments(b);
dialogFragment.show(this.getChildFragmentManager(),
"settings_dialog");
} else {
super.onDisplayPreferenceDialog(preference);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MyAdapter adapter = (MyAdapter) mRv.getAdapter();
int id = item.getItemId();
switch (id) {
case R.id.action_test:
DialogFragment dialog =
(DialogFragment) getChildFragmentManager().findFragmentByTag("dialog");
if (dialog == null) dialog = new MyDialog();
dialog.setTargetFragment(this, REQUEST_RESULT);
dialog.show(getChildFragmentManager(), "dialog");
break;
case R.id.action_refresh:
adapter.notifyAllChanged();
break;
case R.id.action_toggle_expandable_1:
adapter.toggleExpandable(1);
break;
case R.id.action_expand_all:
adapter.expandAllParents();
break;
case R.id.action_collapse_all:
adapter.collapseAllParents();
break;
case R.id.action_expand_1:
adapter.expandParent(1);
break;
case R.id.action_collapse_1:
adapter.collapseParent(1);
break;
}
return super.onOptionsItemSelected(item);
}
public static void show(final FragmentManager fm, final DialogFragment d) {
final FragmentTransaction ft = fm.beginTransaction();
final Fragment prev = fm.findFragmentByTag("dialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
d.show(ft, null);
}
public static void show(AppCompatActivity activity) {
DialogFragment dialogFragment = new ChangeLogDialogFragment();
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(TAG_FRAGMENT);
if (prev != null) {
ft.remove(prev);
}
dialogFragment.show(ft, TAG_FRAGMENT);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
switch ( position )
{
case PLAY_MODE:
MusicApplication application =
(MusicApplication) getActivity().getApplication();
MusicService.MusicBinder musicBinder = application.getMusicBinder();
musicBinder.changePlayMode();
break;
case AUTO_STOP:
getDialog().dismiss(); // 关闭父对话框
DialogFragment dialogFragment = new ASDialogFragment();
FragmentManager manager = getFragmentManager();
dialogFragment.show(manager, "dialog auto stop");
break;
case AUDIO_INFO:
getDialog().dismiss(); // 关闭父对话框
DialogFragment dialogFragment1 = new AIDialogFragment();
FragmentManager manager1 = getFragmentManager();
dialogFragment1.show(manager1, "dialog audio info");
break;
case MORE_INFO:
getDialog().dismiss(); // 关闭父对话框
Toast.makeText(getActivity(), "暂未开发", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
public void closeDialog(String dialogName) {
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
DialogFragment fragment = (DialogFragment) fragmentManager.findFragmentByTag(dialogName);
if(fragment != null) {
fragment.dismiss();
}
}
public void setShowProgress(final boolean showProgress) {
final DialogFragment progress = (DialogFragment) getSupportFragmentManager().findFragmentByTag(TAG_PROGRESS);
if (progress == null && showProgress) {
try {
AptoideDialog.pleaseWaitDialog().show(getSupportFragmentManager(), TAG_PROGRESS);
// https://code.google.com/p/android/issues/detail?id=23761
} catch (IllegalStateException ignore) { }
} else if (progress != null && !showProgress) {
progress.dismissAllowingStateLoss();
}
}
private void dismissIfNecessary(AppCompatActivity context, String tag) {
Fragment frag = context.getSupportFragmentManager().findFragmentByTag(tag);
if (frag != null) {
((DialogFragment) frag).dismiss();
context.getSupportFragmentManager().beginTransaction()
.remove(frag).commit();
}
}