Android official recommendation: DialogFragment dialog box, android creation dialog box

Source: Internet
Author: User

Android official recommendation: DialogFragment dialog box, android creation dialog box

Reprinted please indicate the source: http://blog.csdn.net/lmj623565791/article/details/37815413

1. Overview DialogFragment was introduced when android 3.0 was launched. Is a Special Fragment used to display a modal dialog box on the content of the Activity. It is typically used to display warning boxes, input boxes, confirmation boxes, and so on.
Before DialogFragment is generated, we create a Dialog box: Generally, AlertDialog and Dialog are used. Note: The Dialog create Dialog box is not officially recommended.
2. Benefits and usage use DialogFragment to manage the dialog box. When the revolving screen and press the back key, you can better manage its declaration cycle. It has a basically consistent declaration cycle with Fragment. DialogFragment also allows developers to reuse Dialog as embedded components, similar to Fragment (which can display different effects on large and small screens ). The preceding examples show these benefits ~

To use DialogFragment, you must at least implement the onCreateView or onCreateDIalog method. OnCreateView displays the Dialog using the defined xml layout file. OnCreateDialog: You can use AlertDialog or Dialog to create a Dialog.

3. Override onCreateView to create a Dialog

A) Layout file. We create a layout file with the name set:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content" >    <TextView        android:id="@+id/id_label_your_name"        android:layout_width="wrap_content"        android:layout_height="32dp"        android:gravity="center_vertical"        android:text="Your name:" />    <EditText        android:id="@+id/id_txt_your_name"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_toRightOf="@id/id_label_your_name"        android:imeOptions="actionDone"        android:inputType="text" />    <Button        android:id="@+id/id_sure_edit_name"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentRight="true"        android:layout_below="@id/id_txt_your_name"        android:text="ok" /></RelativeLayout>

B) inherit DialogFragment and override the onCreateView method.

package com.example.zhy_dialogfragment;import android.app.DialogFragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class EditNameDialogFragment extends DialogFragment{@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){View view = inflater.inflate(R.layout.fragment_edit_name, container);return view;}}

C) test run:

Call in the Main method:

public void showEditDialog(View view){EditNameDialogFragment editNameDialog = new EditNameDialogFragment();editNameDialog.show(getFragmentManager(), "EditNameDialog");}
:

As you can see, the dialog box is successfully created and displayed, but the default dialog box has a nasty title. How can we remove it: You can call getDialog () in onCreateView (). requestWindowFeature (Window. FEATURE_NO_TITLE); To remove it. That is:
public class EditNameDialogFragment extends DialogFragment{@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);View view = inflater.inflate(R.layout.fragment_edit_name, container);return view;}}

:
The annoying title is removed perfectly.
4. Override onCreateDialog to create a Dialog in onCreateDialog. Generally, you can use AlertDialog or Dialog to create a Dialog box. However, since google does not recommend using Dialog directly, AlertDialog is used to create a login Dialog box.

A) Layout File

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:orientation="vertical" >    <ImageView        android:layout_width="match_parent"        android:layout_height="64dp"        android:background="#FFFFBB33"        android:contentDescription="@string/app_name"        android:scaleType="center"        android:src="@drawable/title" />    <EditText        android:id="@+id/id_txt_username"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginBottom="4dp"        android:layout_marginLeft="4dp"        android:layout_marginRight="4dp"        android:layout_marginTop="16dp"        android:hint="input username"        android:inputType="textEmailAddress" />    <EditText        android:id="@+id/id_txt_password"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_marginBottom="16dp"        android:layout_marginLeft="4dp"        android:layout_marginRight="4dp"        android:layout_marginTop="4dp"        android:fontFamily="sans-serif"        android:hint="input password"        android:inputType="textPassword" /></LinearLayout>

B) inherit the DialogFragment and override the onCreateDialog method.

package com.example.zhy_dialogfragment;import android.app.AlertDialog;import android.app.Dialog;import android.app.DialogFragment;import android.content.DialogInterface;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.EditText;public class LoginDialogFragment extends DialogFragment{@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState){AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());// Get the layout inflaterLayoutInflater inflater = getActivity().getLayoutInflater();View view = inflater.inflate(R.layout.fragment_login_dialog, null);// Inflate and set the layout for the dialog// Pass null as the parent view because its going in the dialog layoutbuilder.setView(view)// Add action buttons.setPositiveButton("Sign in",new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int id){}}).setNegativeButton("Cancel", null);return builder.create();}}

C) Call

public void showLoginDialog(View view){LoginDialogFragment dialog = new LoginDialogFragment();dialog.show(getFragmentManager(), "loginDialog");}

:


You can see that by rewriting onCreateDialog, you can also create a dialog box, which is nice.

5. pass data to Activity

When data is transmitted from the dialog to the Activity, you can use the "fragment interface pattern" method. The following shows the mode by modifying the logon box above.

The changes are relatively small and the code is directly pasted:

package com.example.zhy_dialogfragment;import android.app.AlertDialog;import android.app.Dialog;import android.app.DialogFragment;import android.content.DialogInterface;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.EditText;public class LoginDialogFragment extends DialogFragment{private EditText mUsername;private EditText mPassword;public interface LoginInputListener{void onLoginInputComplete(String username, String password);}@Overridepublic Dialog onCreateDialog(Bundle savedInstanceState){AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());// Get the layout inflaterLayoutInflater inflater = getActivity().getLayoutInflater();View view = inflater.inflate(R.layout.fragment_login_dialog, null);mUsername = (EditText) view.findViewById(R.id.id_txt_username);mPassword = (EditText) view.findViewById(R.id.id_txt_password);// Inflate and set the layout for the dialog// Pass null as the parent view because its going in the dialog layoutbuilder.setView(view)// Add action buttons.setPositiveButton("Sign in",new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int id){LoginInputListener listener = (LoginInputListener) getActivity();listener.onLoginInputComplete(mUsername.getText().toString(), mPassword.getText().toString());}}).setNegativeButton("Cancel", null);return builder.create();}}

Get the reference of username and password. When you click Login, convert activity into our custom interface: LoginInputListener, and then return the user input data.

In MainActivity, we need to implement our interface loginputlistener to implement our method, so that we can obtain our account password when users click Login:

C) MainActivitypackage com. example. zhy_dialogfragment; import com. example. zhy_dialogfragment.LoginDialogFragment.LoginInputListener; import android. app. activity; import android. app. alertDialog; import android. content. dialogInterface; import android. OS. bundle; import android. view. layoutInflater; import android. view. view; import android. widget. toast; public class MainActivity extends Activity implements loginputlistener {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);} public void showLoginDialog (View view) {LoginDialogFragment diment = new LoginDialogFragment (); dialog. show (getFragmentManager (), "loginDialog") ;}@ Overridepublic void onLoginInputComplete (String username, String password) {Toast. makeText (this, "account:" + username + ", password:" + password, Toast. LENGTH_SHORT ). show ();}}

Effect:


6. DialogFragment for Screen Adaptation

We hope that a dialog box will be displayed in the form of a dialog box on the large screen, while a small screen will be directly embedded in the current Actvity. The dialog box with this effect can only be implemented by rewriting onCreateView. The above EditNameDialogFragment is used for display.

EditNameDialogFragment we have already compiled it and directly write the call in MainActivity

public void showDialogInDifferentScreen(View view){FragmentManager fragmentManager = getFragmentManager();EditNameDialogFragment newFragment = new EditNameDialogFragment();boolean mIsLargeLayout = getResources().getBoolean(R.bool.large_layout) ;Log.e("TAG", mIsLargeLayout+"");if (mIsLargeLayout ){// The device is using a large layout, so show the fragment as a// dialognewFragment.show(fragmentManager, "dialog");} else{// The device is smaller, so show the fragment fullscreenFragmentTransaction transaction = fragmentManager.beginTransaction();// For a little polish, specify a transition animationtransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);// To make it fullscreen, use the 'content' root view as the// container// for the fragment, which is always the root view for the activitytransaction.replace(R.id.id_ly, newFragment).commit();}}

We can see that by reading R. bool. large_layout, and then based on the obtained Boolean value, if it is a large screen, it will be displayed in a dialog box. If it is a small screen, it will be embedded in our Activity layout.

This R. bool. large_layout is the resource file we have defined:

Create a bools. xml file under the default values

<?xml version="1.0" encoding="utf-8"?><resources>    <bool name="large_layout">false</bool></resources>

Create a values-large file under res and create a bools. xml file under values-large.

<?xml version="1.0" encoding="utf-8"?><resources>    <bool name="large_layout">true</bool></resources>

Last test:


Simulator on the left and mobile phone on the right ~~~~~

7. Screen Rotation

When the user enters the account password, the screen is suddenly rotated, And the account password is missing ~~~ Is it crazy?

When the traditional new AlertDialog is rotated on the screen, the user input value is not saved first, and an exception is reported because the dialog box cannot be closed before the Activity is destroyed. The dialog box implemented through DialogFragment does not need to be rotated at all.

We directly copy the logon box created by using AlertDialog and copy it to MainActivity to directly call:

public void showLoginDialogWithoutFragment(View view){AlertDialog.Builder builder = new AlertDialog.Builder(this);// Get the layout inflaterLayoutInflater inflater = this.getLayoutInflater();// Inflate and set the layout for the dialog// Pass null as the parent view because its going in the dialog layoutbuilder.setView(inflater.inflate(R.layout.fragment_login_dialog, null))// Add action buttons.setPositiveButton("Sign in",new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int id){// sign in the user ...}}).setNegativeButton("Cancel", null).show();}

Next, I will click the login box created in two ways to see:


As you can see, the traditional Dialog screen disappears when it is rotated, and the background log reports an exception ~~~ DialogFragment is not affected.



Now, the introduction to DialogFragment is complete ~~~~


Leave a message if you have any questions.


Download source code


Reference:

Http://developer.android.com/guide/topics/ui/dialogs.html#DialogFragment

Https://github.com/thecodepath/android_guides/wiki/Using-DialogFragment


Android development: How does a view class call the dialog box created in the Activity class?

1. Use Context to pass.
Then forcibly convert context to the Activity class to call the function that opens the dialog box, for example (XXOOActivity) context). Open the dialog box ();

2. Custom Listener.
Write the callback call in the View, set the custom Listener for the View in the Activity, and call the function that opens the dialog box in the callback event.

The first type is highly targeted. If this View is repeatedly called by multiple activities, it is very troublesome to handle it. The second type is recommended.

What is the difference between DialogFragment and dialog?

It seems that there is no difference. DialogFragment is another Implementation Method of dialog, but does not know the advantages of DialogFragment? This is the same as the Fragments label. I can achieve similar effects without it, but it may be a little more troublesome to control. For more information, see

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.