WebView is not getting display in the AlerDialog - android

I am trying to display 'WebView' in 'AlertDialog'.
For that I referred one of the question posted here: Displaying WebView in AlertDialog
It successfully opens the dialog window. But I dont know some how its not showing the web content.
This is my 'print_webview' file, which I am inflating in AlertDialog window:
'<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/root">
<WebView
android:id="#+id/dialog_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>'
This is my Java file:
'public class CloudPrintTest extends Activity {
static final int GOOGLE_CLOUD_PRINT_DIALOG = 1; //dialog ID for google cloud print
/** Called when the activity is first created. */
Button printButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
printButton = (Button)findViewById(R.id.button1);
printButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent(CloudPrintTest.this,PrintDialog.class));
showDialog(GOOGLE_CLOUD_PRINT_DIALOG);
}
});
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch(id){
case GOOGLE_CLOUD_PRINT_DIALOG:
//LayoutInflater layoutInflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//final View dialogLayout = layoutInflator.inflate(R.layout.print_webview, null);
LayoutInflater inflater = LayoutInflater.from(CloudPrintTest.this);
View alertDialogView = inflater.inflate(R.layout.print_webview, null);
WebView myWebView = (WebView)alertDialogView.findViewById(R.id.dialog_webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.setWebViewClient(new PrintTestWebViewClient());
myWebView.loadUrl("http://www.google.com/");
AlertDialog.Builder builder = new AlertDialog.Builder(CloudPrintTest.this);
builder.setView(alertDialogView);
builder.setTitle("Google Cloud Print");
builder.setCancelable(true);
AlertDialog printDialog = builder.create();
return printDialog;
}
return null;
}
private class PrintTestWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}'
I have tried all the possible ways, but didnt get the result.
Please help.
Regards

What i would suggest is you creating an activity.
And when you register it in your manifest. Give it the Dialog look with
<activity android:theme="#android:style/Theme.Dialog">

Related

DialogFragment onClick listener doesn't work with ImageButton

I think I tried everything that was provided here. I have ImageButton in my activity and I can't set it to switch to another activity (Log.d shows that it's not even clicked).
Here's my Dialog:
public class StarsActivity extends DialogFragment implements OnClickListener {
Dialog dialog;
Activity mActivity;
ImageButton nextQuestion;
final String LOG_TAG = "myLogs";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_stars, null);
setCancelable(true);
return view;
}
/** The system calls this only when creating the layout in a dialog. */
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
dialog = super.onCreateDialog(savedInstanceState);
//Setting transparency for dialog background
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//No title for dialog
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.activity_stars);
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
nextQuestion = (ImageButton)dialog.findViewById(R.id.nextQuestion);
Log.d(LOG_TAG, nextQuestion.toString());
nextQuestion.setOnClickListener(this);
mActivity = getActivity();
return dialog;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.nextQuestion:
Log.d(LOG_TAG, "Dialog 2: ");
mActivity = getActivity();
Intent i = new Intent(mActivity, FinalActivity.class);
mActivity.startActivity(i);
this.dismiss();
break;
default:
break;
}
}
}
Here's my ImageButton xml:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/nextQuestion"
android:background="#null"
android:src="#drawable/ic_content_nextbutton_02"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp" />
I hope there's a way to solve it.
I think there is No need for you to have an instanse of Dialog in your StarsActivity which is already extending from Dialog fragment.
The below code does everything that you want
public class StarsActivity extends DialogFragment implements View.OnClickListener {
Activity mActivity;
ImageButton nextQuestion;
final String LOG_TAG = "myLogs";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_stars, null);
nextQuestion = (ImageButton)view.findViewById(R.id.nextQuestion);
Log.d(LOG_TAG, nextQuestion.toString());
nextQuestion.setOnClickListener(this);
setCancelable(true);
return view;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.nextQuestion:
Log.d(LOG_TAG, "Dialog 2: ");
mActivity = getActivity();
Intent i = new Intent(mActivity, FinalActivity.class);
mActivity.startActivity(i);
this.dismiss();
break;
default:
break;
}
}
}
Please consider renaming StarsActivity as StarsDialog or something else.
in your Oncreate method add this line :
nextQuestion.setOnClickListener(this);

AlertDialog with a list

I created a alertDialog with a list, but for me keeps indoors.
public class Day extends ListFragment{
private final int IDD_LIST_TIMES = 1;
AlertDialog.Builder builder;
String[] times = { "09:00", "15:00", "19:00", "20:00", "23:00" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TimeAdapter myListAdapter = new TimeAdapter(getActivity(), R.layout.text_fragment, times);
setListAdapter(myListAdapter);
myListAdapter.notifyDataSetChanged();}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView =inflater.inflate(R.layout.listview, container, false);
ListView lv = (ListView)rootView.findViewById(android.R.id.list);
lv.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) { case android.R.id.list:
showDialog(IDD_LIST_TIMES);
break;
}}
});
return rootView;
}
protected Dialog onCreateDialog(int id) {
switch (id) { case IDD_LIST_TIMES:
final String[] mTimes = {"for 5 minutes", "for 10 minutes", "for 15 minutes"};
builder = new AlertDialog.Builder(this);
builder.setTitle("Alarm clock");
builder.setItems(mTimes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"Alarm clock " + mTimes[item],
Toast.LENGTH_SHORT).show();
}});
builder.setCancelable(false);
return builder.create();
default:
return null;
}
}
}
but an error appears constantly for me, where red line "new AlertDialog.Builder(this)"
Why? Prompt me, how to write.
If you want to display a spinner as dialog you can use below code in XML:
<Spinner android:spinnerMode="dropdown" ... />
OR
if you are doing programatically then use:
Spinner sp = new Spinner(this, Spinner.MODE_DIALOG);
OR
If you want to display an ListActivity as Dialog the put this code in your Manifest file:
<activity android:theme="#android:style/Theme.Dialog" />
You are trying to use wrong context object i.e. 'this' which is not applicable for "new AlertDialog.Builder(this)"
First, get the application context in onCreate method and store it into local variable. Use local variable instead of "this" in "new AlertDialog.Builder(this)"
Declare variable
private Context mContext = null;
initialize it in your OnCreate method
#Override
public void onCreate(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mContext = getActivity().getApplicationContext();
Use it in your method
"new AlertDialog.Builder(mContext)"
Hope this will solve your problem.

Custom dialog in custom class returns boolean value

I have searched for the answer and dont find it, so please help me :)
I have a custom class:
public class CustomClass {
private final Context ctx;
public CustomClass(Context ctx) {
this.ctx = ctx;
}
public boolean setDialog(int head, int text) {
final boolean value;
final Dialog d = new Dialog(ctx);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.custom2_dialog);
TextView txtHead = (TextView) d.findViewById(R.id.custom2_txtHead);
txtHead.setText(ctx.getResources().getString(head));
TextView txtText = (TextView) d.findViewById(R.id.custom2_txtText);
txtText.setText(ctx.getResources().getString(text));
Button btnOK = (Button) d.findViewById(R.id.custom2_btnOK);
btnOK.setText("OK");
btnOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
value = true;
d.dismiss();
}
});
Button btnNO = (Button) d.findViewById(R.id.custom2_btnNO);
btnNO.setText("NO");
btnNO.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
value = false;
d.dismiss();
}
});
d.show();
return value;
}
}
You can see that i have a custom dialog created in my custom class because i dont want to create in every activity a dialog. Now when i use it in an Activity:
CustomClass cC = new CustomClass(this);
if(cC.setDialog(R.string.head, R.string.text)) {
// user checked OK
} else {
// user checked NO
}
How to know if user checked OK or NO, because the return true, false value dont work in custom class, the dialog wont wait before the user clicks, it automatic return a value.
Here is the solution to your question.
First of all, if you are creating the Custom dialog then you have to to extend the Dialog class to read the response and implement the OnClickListener.
class CustomizeDialog extends Dialog implements OnClickListener
{
// some code
public CustomizeDialog(Activity activity, String title, String msg, int i, Typeface typeface)
{
super(activity);
this.activity = activity;
intFlag = i;
setContentView(R.layout.relative);
dialogButtonYes = (Button) findViewById(R.id.buttonCustomDialogYes);
dialogButtonNo = (Button) findViewById(R.id.buttonCustomDialogNo);
textView = (TextView) findViewById(R.id.textViewCustomTitle);
this.msg = msg;
dialogButtonNo.setOnClickListener(this);
dialogButtonYes.setOnClickListener(this);
}
}
#Override
public void onClick(View v) {
if (v == dialogButtonYes)
{
Intent intent =new Intent(activity, CallForOne.class);
activity.startActivity(intent);
dismiss();
}
else
dismiss();
}
else if(intFlag == 2)
{
if (v == dialogButtonYes)
{
Intent intent =new Intent(activity, CallMe.class);
activity.startActivity(intent);
dismiss();
}
else
dismiss();
}
And the relative.xml file
<TextView
android:id="#+id/textViewCustomTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/textViewCustomTitle"
android:orientation="horizontal"
android:paddingBottom="1.0dip"
android:paddingLeft="4.0dip"
android:paddingRight="4.0dip"
android:paddingTop="5.0dip" >
<Button
android:id="#+id/buttonCustomDialogYes"
style="#style/styleNormalButton"
android:layout_width="0.0dp"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:text="#string/yes" />
<Button
android:id="#+id/buttonCustomDialogNo"
style="#style/styleNormalButton"
android:layout_width="0.0dp"
android:layout_height="fill_parent"
android:layout_weight="1.0"
android:text="#string/no" />
</LinearLayout>
And the main class
class Main implements OnClickListener
{
onCreate()
{
//your code
}
public void on click()
{
customizeDialog = new CustomizeDialog(CustomDialogExample.this,getString(R.string.title_for_one),getString(R.string.msg_for_one),1,"String");
customizeDialog.show();
}
}
I was facing the same problem here, then I found one solution, to open an Activity from button click in a custom dialog. But you can use this logic for another actions too.
My custom method:
public class Extension extends Activity{
public void showDialogConfirma(Activity localActivity, Class destActivity, String titulo, String mensagem){
final Dialog dialog = new Dialog(localActivity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.dialog_um_btn);
TextView textTitulo = dialog.findViewById(R.id.txtTitle);
textTitulo.setText(titulo);
Button btnOk = dialog.findViewById(R.id.btnOk);
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
// here I can open any activity from any class
localActivity.startActivity(new Intent(localActivity, destActivity));
}
});
dialog.show();
}
}
You call this method like this:
Extension extension = new Extension();
// here you gonna pass your parameters to your Dialog on create it
// on my case the activity that I want open
extension.showDialogConfirma(ThisActivity.this, DestActivity.class, titulo, mensagem);
First of all the comment from #user370305 is the way to do it right. There can be other ways no doubts about that.
The problem you are facing is because when you are calling a method of custom class
if(cC.setDialog(R.string.head, R.string.text));
you are getting the value even though nothing has been clicked
return value;
as false which is the default value set when you are declaring
final boolean value;
Instead you should listen for the Cancel and Ok clicks

Android: How to create a Detail alertdialog

I've been playing around with alert dialogs. I want to show a dialog that shows particular information about a list item in listview. Just like the android's file manager's detail dialog.
Picture: https://dl.dropbox.com/u/20856352/detailsbox.jpg
Interesting thing about this Details dialog is that it shows list items which are very similar to Preference item in a Preferences Screen. They can be clicked upon, they're showing a very nicely laid out two-line item listitem.
I need to create a similar dialog box but I've no clue how to accomplish this. I've played around a bit. Preference XML cannot be used as alertdialog's layout. And I'm unable to develop a layout that looks similar to the above pic. Need help / guideline how to achieve this.
Faraz Azhar
You probably don't want to use a custom dialog because it will be difficult to replicate the look of the AlertDialog. An AlertDialog can display a list of items using AlertDialog.setListAdapter. You can customize the list of items to show two rows of text per item by using a custom implementation of ListAdapter. The attached screenshot was produced by the below code and xml.
public class Temp extends Activity
{
private String[] listItemsFirstRow = {"item 1", "item 2", "item 3"};
private String[] listItemsSecondRow = {"item 1", "item 2", "item 3"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setAdapter(new MyAdapter(), null);
builder.setTitle("Title");
builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
class MyAdapter extends BaseAdapter
{
#Override
public int getCount()
{
return listItemsFirstRow.length;
}
#Override
public Object getItem(int position)
{
//this isn't great
return listItemsFirstRow[position];
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
convertView = getLayoutInflater().inflate(R.layout.main, null);
}
((TextView)convertView.findViewById(R.id.text1)).setText( listItemsFirstRow[position]);
((TextView)convertView.findViewById(R.id.text2)).setText( listItemsSecondRow[position]);
return convertView;
}
}
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:minHeight=![enter image description here][2]"?android:attr/listPreferredItemHeight"
android:orientation="vertical"
android:gravity="center_vertical"
android:paddingLeft="15dip"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="?android:attr/textColorSecondary"
android:id="#+id/text2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Just made your xml file same as regular screen/page
then put this code on your onCreate()
AlertDialog.Builder builder;
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_info,
(ViewGroup) findViewById(R.id.toast_layout_root));
builder = new AlertDialog.Builder(this);
builder.setView(layout);
alertDialog = builder.create();
which r.layout.toast_info is your xml file
and r.id.toast_layout_root is your root xml id (eg. '<'linearlayout android:id="+#id...."'>' )
and when you want to show it just write this line
alertDialog.show();
My suggestion would be to use an Activity as a dialog. This way it is pretty easy to create a custom dialog. Here is a small example which I think you can build upon.
**Activity**
public class CustomDialogEx extends Activity implements OnClickListener {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) { // pass your string data via this intent to the custom view
// show the custom dialog
Intent i = new Intent();
// i.putExtra(<your key/value pairs here>
i.setClass(this, DialogActivity.class);
startActivity(i);
}
}
****************************************************************************
**Custom Dialog**
// The Activity will serve as the Dialog
public class DialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.your_dialog_layout);
Intent i = new Intent();
Bundle b = getIntent().getExtras();
b.getString(<your key>)
}
}
*****************************************************************************
**AndroidManifest**
<activity
android:name="DialogActivity"
android:configChanges="keyboardHidden|orientation"
android:theme="#android:style/Theme.Dialog" >
</activity>
this may also help you
public class ShareDialog extends Dialog implements android.view.View.OnClickListener{
Context mcontContext;
Button btnok;
Listview lstview;
public ShareDialog(Context context) {
super(context);
mcontContext= context;
//pls replace with your dialog.xml file
setContentView(R.layout.sharedialog);
bindComponent();
addListener();
}
private void bindComponent() {
// TODO Auto-generated method stub
lstview=(Listview) findViewById(R.id.lstdetail);
btnok=(Button) findViewById(R.id.btnok);
//bind here listview with your adpter
}
private void addListener()
{
btnshareviwifi.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnok:
dismiss();
break;
default:
break;
}
}
}
and where you want to show
ShareDialog shobje=new ShareDialog (context);
shobje.show()

Android Dialog reopen after rotate device

I'm writing a very simple application to open my custom share dialog.
XML layout contains only 1 button:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/white"
android:gravity="center_horizontal">
<Button android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_margin="20dip"
android:text="Click here to open Share Dialog"
android:onClick="onBtnShareClick"/>
</LinearLayout>
And on Activity, I create a custom sharing Dialog
public class CustomDialog extends Activity {
private static final int SHOW_DIALOG_SHARE = 1;
private ArrayAdapter<ShareItem> mShareAdapter;
#Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.custom_dialog);
final ShareItem[] items = {
//new Item("Menu item", R.drawable.icon_assistance),
new ShareItem("Banbe", R.drawable.ic_banbe),
new ShareItem("Facebook", R.drawable.ic_facebook),
new ShareItem("Twitter", R.drawable.ic_twitter),
new ShareItem("Gmail", R.drawable.ic_gmail),
new ShareItem("Other sharing options...", 0)
};
mShareAdapter = new ArrayAdapter<ShareItem>(
this,
android.R.layout.select_dialog_item,
android.R.id.text1,
items){
public View getView(int position, View convertView, ViewGroup parent) {
//User super class to create the View
View v = super.getView(position, convertView, parent);
TextView tv = (TextView)v.findViewById(android.R.id.text1);
//Put the image on the TextView
tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);
//Add margin between image and text (support various screen densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
tv.setCompoundDrawablePadding(dp5);
return v;
}
};
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case SHOW_DIALOG_SHARE:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(R.string.app_name)
.setAdapter(mShareAdapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(CustomDialog.this, "Click on item " + item, Toast.LENGTH_SHORT).show();
}
})
.show();
}
return null;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onRestoreInstanceState(savedInstanceState);
}
public void onBtnShareClick(View v) {
showDialog(SHOW_DIALOG_SHARE);
}
protected class ShareItem {
public final String text;
public final int icon;
public ShareItem(String text, Integer icon) {
this.text = text;
this.icon = icon;
}
#Override
public String toString() {
return text;
}
}
}
When click the button, my Sharing Dialog will be opened. All good.
Now, I rotate the device to portrait mode, click the button to open the Dialog. After that, press back to close Sharing Dialog. Rotate device to landscape mode. Suddenly Sharing Dialog is re-opened although I didn't click on the button.
When I try using the native Sharing Dialog I don't see this bug. Maybe a custom Sharing Dialog is the cause?
Can anyone tell me what's wrong here?
Hi You have to add screen orientation support in your application manifest file.
<activity android:name=".TestApp"
android:label="#string/app_name" android:configChanges="orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
And also override the following method ,
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
use create() method instead of show() method
new AlertDialog.Builder(this).create()
Try use own class that will be extends from DialogFragment
For example:
public class QuestionDialogFragment extends DialogFragment
{
public final static String BF_TITLE = "QuestionDialogFragment.BF_TITLE";
public final static String BF_QUESTION = "QuestionDialogFragment.BF_QUESTION";
private Callback mCallback;
public static void init(FragmentManager fragmentManager, String title, String question, Callback callback)
{
Bundle bundle = new Bundle();
bundle.putString(BF_TITLE, title);
bundle.putString(BF_QUESTION, question);
QuestionDialogFragment dialog = new QuestionDialogFragment();
dialog.setCallbackListener(callback);
dialog.setArguments(bundle);
dialog.show(fragmentManager, null);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setCancelable(false);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Bundle bundle = getArguments();
String title = null;
String question = null;
if (bundle != null)
{
if (bundle.containsKey(BF_TITLE))
{
title = bundle.getString(BF_TITLE);
}
if (bundle.containsKey(BF_QUESTION))
{
question = bundle.getString(BF_QUESTION);
}
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity());
alertDialogBuilder.setTitle(title);
alertDialogBuilder.setMessage(question);
//null should be your on click listener
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
mCallback.success();
dialog.dismiss();
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
mCallback.cancel();
dialog.cancel();
}
});
return alertDialogBuilder.create();
}
public void setCallbackListener(Callback callback)
{
this.mCallback = callback;
}
public static interface Callback
{
void success();
void cancel();
}
}
And use it anywhere in your code:
QuestionDialogFragment.init(
getFragmentManager(),
"Some title",
"Some question?",
new QuestionDialogFragment.Callback()
{
#Override
public void success()
{
// #TODO if user choice YES;
}
#Override
public void cancel()
{
// #TODO if user choice CANCEL;
}
});
If you want create own view instead standard dialog window just instead:
Dialog onCreateDialog(Bundle savedInstanceState)
use
View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
For example:
need create values/layout/your_fragment_layout.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/kom_purchase_dialog_root_view">
<TextView
android:id="#+id/kom_purchase_dialog_message_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="some text"/>
<LinearLayout
android:layout_gravity="bottom"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/kom_purchase_dialog_negative_button"
android:layout_alignParentBottom="true"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Cancel"/>
<Button
android:id="#+id/kom_purchase_dialog_positive_button"
android:layout_toRightOf="#+id/kom_purchase_dialog_negative_button"
android:layout_alignParentBottom="true"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Ok"/>
</LinearLayout>
</FrameLayout>
and for this layout change own class as:
public class QuestionDialogFragment2 extends DialogFragment
{
public final static String BF_TITLE = "QuestionDialogFragment.BF_TITLE";
public final static String BF_QUESTION = "QuestionDialogFragment.BF_QUESTION";
private Callback mCallback;
public static void init(FragmentManager fragmentManager, String title, String question, Callback callback)
{
Bundle bundle = new Bundle();
bundle.putString(BF_TITLE, title);
bundle.putString(BF_QUESTION, question);
QuestionDialogFragment2 dialog = new QuestionDialogFragment2();
dialog.setCallbackListener(callback);
dialog.setArguments(bundle);
dialog.show(fragmentManager, null);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setCancelable(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
Bundle bundle = getArguments();
String title = null;
String question = null;
if (bundle != null)
{
if (bundle.containsKey(BF_TITLE))
{
title = bundle.getString(BF_TITLE);
}
if (bundle.containsKey(BF_QUESTION))
{
question = bundle.getString(BF_QUESTION);
}
}
View view = super.onCreateView(inflater, container, savedInstanceState);
if (view == null)
{
view = inflater.inflate(R.layout.your_fragment_layout, null, false);
view.setTag(new Holder(view));
}
Holder holder = (Holder) view.getTag();
holder.messageTextView.setText(question);
holder.positiveButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mCallback.success();
}
});
holder.negativeButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
mCallback.cancel();
}
});
return view;
}
public void setCallbackListener(Callback callback)
{
this.mCallback = callback;
}
public static interface Callback
{
void success();
void cancel();
}
private final class Holder
{
public TextView messageTextView;
public Button positiveButton;
public Button negativeButton;
private Holder(View view)
{
messageTextView = (TextView) view.findViewById(R.id.question_dialogfragment_message_textview);
positiveButton = (Button) view.findViewById(R.id.question_dialogfragment_positive_button);
negativeButton = (Button) view.findViewById(R.id.question_dialogfragment_negative_button);
}
}
}
and the same usage:
QuestionDialogFragment2.init(
getFragmentManager(),
"Some title",
"Some question?",
new QuestionDialogFragment2.Callback()
{
#Override
public void success()
{
// #TODO if user choice YES;
}
#Override
public void cancel()
{
// #TODO if user choice CANCEL;
}
});
For both approaches will work void onSaveInstanceState(Bundle outState) and save state after rotation. I think it's better and universal approach then user the simple dialog.
It doesn't matter if Dialog or AlertDialog was used. In order to avoid closing the dialog when you rotate screen, use this code:
dialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

Categories

Resources