Android fragment show as dialogfragment or usual fragment

前端 未结 3 1511
夕颜
夕颜 2020-12-30 06:10

What I am trying to achieve is to have a fragment that on tablet it shows as a DialogFragment, while on smartphone it would be shown as a regular fragment. I am

3条回答
  •  渐次进展
    2020-12-30 06:32

    This issue can be easily fixed if instead of trying to make a Fragment look like a DialogFragment I would look from the opposite angle: make a DialogFragment look like a Fragment - after all, a DialogFragment is a Fragment!

    The key of this fix is to call or not DialogFragment.setShowsDialog();

    So changing the DetailedFragment to:

    public class DetailedFragment extends DialogFragment {
    
        private static final String ARG_SHOW_AS_DIALOG = "DetailedFragment.ARG_SHOW_AS_DIALOG";
    
        public static DetailedFragment newInstance(boolean showAsDialog) {
            DetailedFragment fragment = new DetailedFragment();
            Bundle args = new Bundle();
            args.putBoolean(ARG_SHOW_AS_DIALOG, showAsDialog);
            fragment.setArguments(args);
            return fragment;
        }
    
        public static DetailedFragment newInstance() {
            return newInstance(true);
        }
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Bundle args = getArguments();
            if (args != null) {
                setShowsDialog(args.getBoolean(ARG_SHOW_AS_DIALOG, true));
            }
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            return inflater.inflate(R.layout.detailed_fragment, container, false);
        }
    }
    

    its layout remains as it was, DetailedActivity changes to:

    public class DetailedActivity extends ActionBarActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.detailed_activity);
            if (savedInstanceState == null) {
                DetailedFragment fragment = DetailedFragment.newInstance(false);
                getSupportFragmentManager().beginTransaction().add(R.id.root_layout_details, fragment, "Some_tag").commit();
            }
        }
    }
    

    its layout as well:

    
    

    and the caller activity does only:

    private void decideToNext() {
        String device = getString(R.string.device);
        if ("normal".equalsIgnoreCase(device)) {
            Intent intent = new Intent(this, DetailedActivity.class);
            startActivity(intent);
        } else if ("large".equalsIgnoreCase(device)) {
            DetailedFragment fragment = DetailedFragment.newInstance();
            fragment.show(getSupportFragmentManager(), "Tablet_specific");
        }
    }
    

提交回复
热议问题