欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android中使用DialogFragment編寫對(duì)話框的實(shí)例教程

 更新時(shí)間:2016年04月18日 16:09:03   作者:鴻洋_  
這篇文章主要介紹了Android中使用DialogFragment編寫對(duì)話框的實(shí)例教程,DialogFragment也是一種Fragment,因而管理生命周期時(shí)比較給力,需要的朋友可以參考下

Android提供alert、prompt、pick-list,單選、多選,progress、time-picker和date-picker對(duì)話框,并提供自定義的dialog。在Android 3.0后,dialog基于fragment,并對(duì)之前版本提供兼容支持庫,也就是說對(duì)于開發(fā)者而言,dialog是基于DialogFragment的,但此時(shí)需要在應(yīng)用中加入相關(guān)的兼容庫。
和Windows或者網(wǎng)頁JS的Dialog不同,Android的dialog是異步的,而不是同步的。對(duì)于同步的dialog,顯示dialog后,下一行代碼會(huì)等到dialog結(jié)束,即下一行代碼可以知道dialog的輸入以及用戶點(diǎn)擊的button。而對(duì)于異步的dialog,dialog顯示后,下一行代碼繼續(xù)執(zhí)行,而不是等dialog消失,通過callback來處理dialog的事件。異步的dialog也意味著應(yīng)用的代碼也可以關(guān)閉dialog。

使用DialogFragment來管理對(duì)話框,當(dāng)旋轉(zhuǎn)屏幕和按下后退鍵時(shí)可以更好的管理其聲明周期,它和Fragment有著基本一致的聲明周期。且DialogFragment也允許開發(fā)者把Dialog作為內(nèi)嵌的組件進(jìn)行重用,類似Fragment(可以在大屏幕和小屏幕顯示出不同的效果)。上面會(huì)通過例子展示這些好處~
使用DialogFragment至少需要實(shí)現(xiàn)onCreateView或者onCreateDIalog方法。onCreateView即使用定義的xml布局文件展示Dialog。onCreateDialog即利用AlertDialog或者Dialog創(chuàng)建出Dialog。

下面我們就來看一個(gè)使用DialogFragment編寫對(duì)話框的例子:
1.重寫onCreateView創(chuàng)建Dialog
a)布局文件,我們創(chuàng)建一個(gè)設(shè)置名稱的布局文件:

<?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)繼承DialogFragment,重寫onCreateView方法

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 
{ 
 
 
  @Override 
  public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) 
  { 
    View view = inflater.inflate(R.layout.fragment_edit_name, container); 
    return view; 
  } 
 
} 

c)測試運(yùn)行:
Main方法中調(diào)用:

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

效果圖:

2016418160349253.jpg (224×383)

可以看到,對(duì)話框成功創(chuàng)建并顯示出來,不過默認(rèn)對(duì)話框有個(gè)討厭的標(biāo)題,我們?cè)趺慈サ裟兀嚎梢栽趏nCreateView中調(diào)用getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);即可去掉。即:

public class EditNameDialogFragment extends DialogFragment 
{ 
 
  @Override 
  public 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; 
  } 
 
} 

效果圖:

2016418160425535.jpg (407×653)

很完美的去掉了討厭的標(biāo)題。

2.重寫onCreateDialog創(chuàng)建Dialog
在onCreateDialog中一般可以使用AlertDialog或者Dialog創(chuàng)建對(duì)話框,不過既然google不推薦直接使用Dialog,我們就使用AlertDialog來創(chuàng)建一個(gè)登錄的對(duì)話框。
a)布局文件

<?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)繼承DialogFragment重寫onCreateDialog方法

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 
{ 
 
  @Override 
  public Dialog onCreateDialog(Bundle savedInstanceState) 
  { 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    // Get the layout inflater 
    LayoutInflater 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 layout 
    builder.setView(view) 
        // Add action buttons 
        .setPositiveButton("Sign in", 
            new DialogInterface.OnClickListener() 
            { 
              @Override 
              public void onClick(DialogInterface dialog, int id) 
              { 
              } 
            }).setNegativeButton("Cancel", null); 
    return builder.create(); 
  } 
} 

c)調(diào)用

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

效果圖:

2016418160523326.jpg (409×567)

可以看到通過重寫onCreateDialog同樣可以實(shí)現(xiàn)創(chuàng)建對(duì)話框,效果還是很nice的。

3.傳遞數(shù)據(jù)給Activity
從dialog傳遞數(shù)據(jù)給Activity,可以使用“fragment interface pattern”的方式,下面通過一個(gè)改造上面的登錄框來展示這種模式。
改動(dòng)比較小,直接貼代碼了:

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); 
  } 
   
  @Override 
  public Dialog onCreateDialog(Bundle savedInstanceState) 
  { 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    // Get the layout inflater 
    LayoutInflater 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 layout 
    builder.setView(view) 
        // Add action buttons 
        .setPositiveButton("Sign in", 
            new DialogInterface.OnClickListener() 
            { 
              @Override 
              public void onClick(DialogInterface dialog, int id) 
              { 
                LoginInputListener listener = (LoginInputListener) getActivity(); 
                listener.onLoginInputComplete(mUsername 
                    .getText().toString(), mPassword 
                    .getText().toString()); 
              } 
            }).setNegativeButton("Cancel", null); 
    return builder.create(); 
  } 
} 

拿到username和password的引用,在點(diǎn)擊登錄的時(shí)候,把a(bǔ)ctivity強(qiáng)轉(zhuǎn)為我們自定義的接口:LoginInputListener,然后將用戶輸入的數(shù)據(jù)返回。
MainActivity中需要實(shí)現(xiàn)我們的接口LoginInputListener,實(shí)現(xiàn)我們的方法,就可以實(shí)現(xiàn)當(dāng)用戶點(diǎn)擊登陸時(shí),獲得我們的帳號(hào)密碼了:

c)  MainActivity 

package 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 LoginInputListener 
{ 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) 
  { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
  } 
 
   
 
  public void showLoginDialog(View view) 
  { 
    LoginDialogFragment dialog = new LoginDialogFragment(); 
    dialog.show(getFragmentManager(), "loginDialog"); 
 
  } 
 
  @Override 
  public void onLoginInputComplete(String username, String password) 
  { 
    Toast.makeText(this, "帳號(hào):" + username + ", 密碼 :" + password, 
        Toast.LENGTH_SHORT).show(); 
  } 
 
} 

效果:

4.DialogFragment做屏幕適配
我們希望,一個(gè)對(duì)話框在大屏幕上以對(duì)話框的形式展示,而小屏幕上則直接嵌入當(dāng)前的Actvity中。這種效果的對(duì)話框,只能通過重寫onCreateView實(shí)現(xiàn)。下面我們利用上面的EditNameDialogFragment來顯示。
EditNameDialogFragment我們已經(jīng)編寫好了,直接在MainActivity中寫調(diào)用

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 
      // dialog 
      newFragment.show(fragmentManager, "dialog"); 
    } else 
    { 
      // The device is smaller, so show the fragment fullscreen 
      FragmentTransaction transaction = fragmentManager 
          .beginTransaction(); 
      // For a little polish, specify a transition animation 
      transaction 
          .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 activity 
      transaction.replace(R.id.id_ly, newFragment) 
          .commit(); 
    } 
  } 

可以看到,我們通過讀取R.bool.large_layout,然后根據(jù)得到的布爾值,如果是大屏幕則直接以對(duì)話框顯示,如果是小屏幕則嵌入我們的Activity布局中
這個(gè)R.bool.large_layout是我們定義的資源文件:
在默認(rèn)的values下新建一個(gè)bools.xml

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

然后在res下新建一個(gè)values-large,在values-large下再新建一個(gè)bools.xml

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

最后測試:

2016418160640929.jpg (399×308)2016418160659159.jpg (373×559)

左邊為模擬器,右邊為我的手機(jī)~~~~~

5.屏幕旋轉(zhuǎn)
當(dāng)用戶輸入帳號(hào)密碼時(shí),忽然旋轉(zhuǎn)了一下屏幕,帳號(hào)密碼不見了~~~是不是會(huì)抓狂
傳統(tǒng)的new AlertDialog在屏幕旋轉(zhuǎn)時(shí),第一不會(huì)保存用戶輸入的值,第二還會(huì)報(bào)異常,因?yàn)锳ctivity銷毀前不允許對(duì)話框未關(guān)閉。而通過DialogFragment實(shí)現(xiàn)的對(duì)話框則可以完全不必考慮旋轉(zhuǎn)的問題。
我們直接把上面登錄使用AlertDialog創(chuàng)建的登錄框,拷貝到MainActivity中直接調(diào)用:

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

下面我分別點(diǎn)擊兩種方式創(chuàng)建的登錄框,看效果圖:

可以看到,傳統(tǒng)的Dialog旋轉(zhuǎn)屏幕時(shí)就消失了,且后臺(tái)log會(huì)報(bào)異常~~~使用DialogFragment則不受影響。

PS:再談fragment管理器
通過fragment管理器或者fragment transaction,我們可以對(duì)dialog fragment進(jìn)行具體地控制。show()就是在管理器中加入fragment,dismiss()就是從管理器中去掉fragment。我們不能先進(jìn)行add(),然后在進(jìn)行show(),因此一個(gè)fragment對(duì)象只能加入管理器一次。如果fragment被dismiss(),將從管理器中刪除,我們不能再通過管理器獲取該fragment的信息。因此,如果我們想保留被dismiss的dialog的一些狀態(tài)或信息,需要在dialog外進(jìn)行保存,例如利用activity。
總結(jié):
編程思想:封裝接口
在小例子中,fragment會(huì)調(diào)用activity的onDialogDone()來顯示Toast等信息。在真正項(xiàng)目中,fragment的編寫并不需要了解activity的各類方法,好的編程風(fēng)格是將fragment所涉及的方法以接口的方式封裝起來,如下:

public interface OnMyDialogClickListener { 
  public void onDialogDone(String tag, boolean cancelled, CharSequence message);
}

在activity中,增加接口的實(shí)現(xiàn),如下:

public class MainActivity extends Activity implements OnMyDialogClickListener{
  ......   
  public void onDialogDone(String tag, boolean cancelled, CharSequence message) {
    String s = tag + " responds with: " + message;
    if(cancelled) 
      s = tag + " was cancelled by the user"; 
    Toast.makeText(this, s, Toast.LENGTH_LONG).show(); 
    showInfo(s); 
  } 
}

相應(yīng)地,在fragment中,對(duì)該方法的調(diào)用,可以寫為:

OnMyDialogClickListener act = (OnMyDialogClickListener)getActivity(); 
act.onDialogDone(……); 

對(duì)于一些大型項(xiàng)目,如果我們無法確定activity是否真的實(shí)現(xiàn)了接口,可以在fragment的早期,即剛關(guān)聯(lián)activity的階段進(jìn)行檢測,如下:

@Override 
public void onAttach(Activity activity) { 
  //onAttach()是合適的早期階段進(jìn)行檢查MyActivity是否真的實(shí)現(xiàn)了接口。
  //采用接口的方式,dialog無需詳細(xì)了解MyActivity,只需了解其所需的接口函數(shù),這是真正項(xiàng)目中應(yīng)采用的方式。 
  try{ 
    OnMyDialogClickListener act = (OnMyDialogClickListener)activity; 
  }catch(ClassCastException e){
    …... activity并不真正支持接口的異常處理...... 
  } 
  super.onAttach(activity); 
} 

fragment和activity以其他fragment之間的通信:
小例子演示了通過getActivity()獲取接口對(duì)象或者直接獲取activity的對(duì)象,實(shí)現(xiàn)兩者之間的通信。此外fragment也可以通過fragment管理器,通過tag,獲取其他fragment實(shí)例,從而進(jìn)行fragment之間的通信。當(dāng)然從編程思想的角度看,fragment之間的過多進(jìn)行交叉調(diào)用,不利于程序的管控。

相關(guān)文章

最新評(píng)論