Skip to content

Instantly share code, notes, and snippets.

@Jeevuz
Last active January 18, 2017 10:19
Show Gist options
  • Save Jeevuz/7ff51d3ca5ae3d055773fd522b8b2f1b to your computer and use it in GitHub Desktop.
Save Jeevuz/7ff51d3ca5ae3d055773fd522b8b2f1b to your computer and use it in GitHub Desktop.
Dialog to ask for string to enter
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:layout_marginTop="8dp"
android:maxLength="64"
tools:text="Hello">
</EditText>
</FrameLayout>
package ru.mobileup.myalarm2.ui.dialog;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.widget.EditText;
import ru.mobileup.myalarm2.R;
/**
* Dialog to ask for string to enter
* @author Vasili Chyrvon ([email protected])
*/
public class EnterStringDialogFragment extends AppCompatDialogFragment {
private static final String ARGS_TITLE_RES_ID = "args_title";
private static final String ARGS_HINT = "args_hint";
private OnStringEnteredListener mListener;
private EditText mEditText;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnStringEnteredListener) getParentFragment();
} catch (ClassCastException e) {
throw new ClassCastException(getParentFragment().toString() + " must implement OnStringEnteredListener");
}
}
public static EnterStringDialogFragment newInstance(@StringRes int titleResId, String hint) {
Bundle args = new Bundle();
args.putInt(ARGS_TITLE_RES_ID, titleResId);
args.putString(ARGS_HINT, hint);
EnterStringDialogFragment fragment = new EnterStringDialogFragment();
fragment.setArguments(args);
return fragment;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getContext())
.setTitle(getArguments().getInt(ARGS_TITLE_RES_ID))
.setView(R.layout.dialog_custom_edit_text)
.setPositiveButton(R.string.save, (dialog, which) -> mListener.onStringEntered(mEditText.getText().toString()))
.setNegativeButton(R.string.cancel, (dialog, which) -> dismiss())
.create();
}
@Override
public void onStart() {
super.onStart();
mEditText = (EditText) getDialog().findViewById(R.id.edit_text);
mEditText.setHint(getArguments().getString(ARGS_HINT));
}
public interface OnStringEnteredListener {
void onStringEntered(String string);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment