CreaaZ
CreaaZ

Reputation: 13

Android - How use Fragment as Dialog or Activity depending on device

I'm very new to Android programming and I'm stuck at a point where I want to finish my UI development. The picture in this question simply explains my problem: Dialog fragment embedding depends on device

I want to create a reusable UI component with a Layout (probably LinearLayout or Relative Layout). Depending on the screen size (Tablet vs. Phone) I want to open the UI component in a Dialog or in a separate Activity.

Can anyone of you give me an advice how to achieve this?

Upvotes: 1

Views: 2768

Answers (2)

Karan Khurana
Karan Khurana

Reputation: 585

In the activity you want to use fragment type :

FragmentManager fm = getSupportFragmentManager();
//fragment class name : DFragment
DFragment dFragment = new DFragment();
            // Show DialogFragment
            dFragment.show(fm, "Welcome to dialog fragment!!");

Now create a class DFragment and type :

public class DFragment extends DialogFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.dialogfragment, container,
            false);
    getDialog().setTitle("DialogFragment Tutorial");        
    // Do something else
    return rootView;
}
}

dialogfragment.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:padding="10dp"
    android:text="@string/welcome" />
</RelativeLayout>

Hope it helps!!

Upvotes: 4

Gonzalo
Gonzalo

Reputation: 1876

If you are using android studio you can create a new master/detail activity to see how they resolve this.

What you could do is to create a layout with 2 configs, one for phone and other for tablets (adding width attributes for example). In the tablet layout you can add the FrameLayout where you are going to host the fragment.

In the onCreate() of the activity you can check if that FrameLayout exits. If it does set a variable to true fragmentView = true and check that where you are creating the fragment or launching the activity.

Upvotes: 0

Related Questions