[英]how to implement dialogfragment in fragment?
我有一個關於dialogfragment的問題-我通過教程創建了一個使用dialogfragment的類,但是在本教程中,單擊按鈕顯示了dialogfragment-我想通過單擊MainActivity中的fragment選項卡顯示dialogfragment ..我有Fragment GetItem方法,其中我的代碼中有空的case 4-這是片段,我想通過單擊它來打開dialogfragment。 有我的密碼。 感謝您提供的所有幫助和答案! 很抱歉,如果不清楚。
-問題已修復(即注釋)-我創建了新的DialogFragment-xml文件和Java類-來自guides.codepath.com/android/Using-DialogFragment#build-dialog的代碼,然后將此代碼添加至MainActivity
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
int position = tab.getPosition();
if (position == 4) {
showAlertDialog();
}
}
});
}
private void showAlertDialog() {
FragmentManager fm = getSupportFragmentManager();
EditNameDialogFragment alertDialog = EditNameDialogFragment.newInstance("Some title");
alertDialog.show(fm, "fragment_alert");
}
您可能想檢測單擊了哪個選項卡,然后像其他任何對話框一樣顯示對話框
您需要添加一個TabLayout.OnTabSelectedListener
設置
tabLayout.setupWithViewPager(mViewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager) {
@Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
int position = tab.getPosition();
if (position == 4) {
// Create MediaFragment here
}
}
});
參見android 示例 :
public static class MyAlertDialogFragment extends DialogFragment {
public static MyAlertDialogFragment newInstance(int title) {
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.alert_dialog_icon)
.setTitle(title)
.setPositiveButton(R.string.alert_dialog_ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialog)getActivity()).doPositiveClick();
}
}
)
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialog)getActivity()).doNegativeClick();
}
}
)
.create();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.