來到 Android 3, 蜂巢(Honeycomb), 為支持應用程序中的多個活動間(multiple activities)的UI和邏輯重用, showDialog()和dismissDialog()方法被棄用, 取而代之的是對話片段(DialogFragment).
實現話片段(DialogFragment), 先創建它的佈局文件和擴展 DialogFragment 類.
實現話片段(DialogFragment)的佈局文件, /res/layout/dialogfragments.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="I'm Dialog Fragment" /> <ImageView android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>
創建擴展 DialogFragment 的類, MyDialogFragment.java.
package com.Android3DialogFragments; import android.app.DialogFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class MyDialogFragment extends DialogFragment { public MyDialogFragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View myDialogFragmentView = inflater.inflate(R.layout.dialogfragments, container); getDialog().setTitle("MyDialogFragment"); return myDialogFragmentView; } }
修改主佈局main.xml, 添加一個按鈕打開對話片段.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <Button android:id="@+id/opendialogfragment" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Open Dialog Fragment" /> </LinearLayout>
主活動的Java代碼
package com.Android3DialogFragments; import android.app.Activity; import android.app.FragmentManager; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Android3DialogFragmentsActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button openDialogFragment = (Button)findViewById(R.id.opendialogfragment); openDialogFragment.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { openMyDialogFragment(); }}); } private void openMyDialogFragment(){ FragmentManager fragmentManager = getFragmentManager(); MyDialogFragment myDialogFragment = new MyDialogFragment(); myDialogFragment.show(fragmentManager, "tag_myDialogFragment"); } }
沒有留言:
發佈留言