Skip to content Skip to sidebar Skip to footer

How To Show Different Layouts Inside Fragments

I am working with two fragments in Android Honeycomb (Tab). In the left is a ListView and in the right is a preview of the item selected from the list. When one of the buttons is c

Solution 1:

You can do this, I made the same thing with use of these links, here is my code which I am sharing with you in the hope that it will be helpful for you... You will first have to create 4 layouts. 2 of which will be for landscape mode, one for portrait mode and another for tablets. You have to create a couple more folders for layouts and their name should be like layout-xlarge and layout-xlarge-port, this way you can create fragments for both mobile devices and tablets.

MasterFragment Activity:

publicclassMasterFragmentextendsListFragment {
    Boolean isDualPane;
    int position;

    @OverridepublicvoidonActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ArrayList<String> parkNames = newArrayList<String>();
        for (Park park : Resort.PARKS) {
            parkNames.add(park.getName());
        }

        setListAdapter(newArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, parkNames));
        ViewdetailFrame= getActivity().findViewById(R.id.detail);
        isDualPane = detailFrame != null && detailFrame.getVisibility() == View.VISIBLE;

        if (savedInstanceState != null) {
            position = savedInstanceState.getInt("position", 0);
        }

        if (isDualPane) {
            getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            showDetail(position);
        }
    }

    @OverridepublicvoidonSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("position", position);
    }

    @OverridepublicvoidonListItemClick(ListView l, View v, int position, long id) {
        showDetail(position);
    }

    voidshowDetail(int position) {
        this.position = position;
        if (isDualPane) {
            getListView().setItemChecked(position, true);
            DetailFragmentdetailFragment= (DetailFragment) getFragmentManager()
                    .findFragmentById(R.id.detail);

            if (detailFragment == null || detailFragment.getIndex() != position) {
                detailFragment = newDetailFragment(position);
                FragmentTransactionft= getFragmentManager()
                        .beginTransaction();
                ft.replace(R.id.detail, detailFragment);
                ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                ft.commit();
            }
        } else {
            Intentintent=newIntent();
            intent.setClass(getActivity(), DetailActivity.class);
            intent.putExtra("position", position);
            startActivity(intent);
        }
    }
}        

Second Activity - DetailFragment Activity:

publicclassDetailActivityextendsFragmentActivity {

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.detail_act);
        Bundlebundle= getIntent().getExtras();
        intposition= bundle.getInt("position");
        System.out.println("RR : position is : " + position);

        Integer[] images = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
                R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
                R.drawable.pic7, R.drawable.pic8, R.drawable.pic9,
                R.drawable.pic10, R.drawable.pic11, R.drawable.pic12,
                R.drawable.pic13 };

        finalImageViewimgview= (ImageView) findViewById(R.id.imageView1);
        imgview.setImageResource(images[position]);

        // DetailFragment detailFragment = new DetailFragment(position);// FragmentManager fm = getSupportFragmentManager();// FragmentTransaction ft =fm.beginTransaction();// ft.add(android.R.id.content, detailFragment).commit();

    }
}

Now you have to create a third activity, MasterGridActivity for my images which I am using for showing in fragment in GridView.

publicclassMasterGridActivityextendsFragment {

    Boolean isDualPane;
    GridView gridView;
    ListView listView;
    int position;

    @OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Viewview= inflater.inflate(R.layout.gridview, container, false);

        gridView = (GridView) view.findViewById(R.id.gridViewImage);
        gridView.setAdapter(newMyAdapter(view.getContext()));

        return view;
    }

    @OverridepublicvoidonActivityCreated(Bundle savedInstanceState) {
        ViewdetailFrame= getActivity().findViewById(R.id.detail);

        isDualPane = detailFrame != null && detailFrame.getVisibility() == View.VISIBLE;

        gridView.setOnItemClickListener(newOnItemClickListener() {

            @OverridepublicvoidonItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                if (!isDualPane) {
                    Intentintent=newIntent();
                    intent.setClass(getActivity(), DetailActivity.class);
                    intent.putExtra("position", pos);
                    startActivity(intent);
                } else {
                    DetailFragmentdetailFragment= (DetailFragment) getFragmentManager().findFragmentById(R.id.detail);

                    if (detailFragment == null || detailFragment.getIndex() != pos) {

                        detailFragment = newDetailFragment(pos);
                        FragmentTransactionft= getFragmentManager().beginTransaction();

                        ft.replace(R.id.detail, detailFragment);
                        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                        ft.commit();
                    }
                }
            }
        });

        super.onActivityCreated(savedInstanceState);
    }
}

Now here is my image adapter - MyAdapter - for my images which extends a BaseAdapter.

publicclassMyAdapterextendsBaseAdapter {

    private Context mContext;

    publicMyAdapter(Context c) {
        mContext = c;
    }

    @OverridepublicintgetCount() {
        return mThumbIds.length;
    }

    @Overridepublic Object getItem(int arg0) {
        returnnull;
    }

    @OverridepubliclonggetItemId(int position) {
        return0;
    }

    @Overridepublic View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) { // if it's not recycled, initialize some attributes
            imageView = newImageView(mContext);
            imageView.setLayoutParams(newGridView.LayoutParams(100, 100));
            imageView.setImageResource(mThumbIds[position]);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(0, 0, 0, 0);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    static Integer[] mThumbIds = { R.drawable.pic1, R.drawable.pic2,
            R.drawable.pic3, R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
            R.drawable.pic7, R.drawable.pic8, R.drawable.pic9,
            R.drawable.pic10, R.drawable.pic11, R.drawable.pic12,
            R.drawable.pic13,
    };
}

Now I am sharing the XML files for these fragments.

Main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal"><fragmentandroid:id="@+id/master"android:layout_width="match_parent"android:layout_height="match_parent"class="org.fragment.MasterGridActivity" /></LinearLayout>

gridview.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><GridViewxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/gridViewImage"android:layout_width="fill_parent"android:layout_height="fill_parent"android:numColumns="auto_fit"android:columnWidth="90dp"android:horizontalSpacing="10dp"android:verticalSpacing="10dp"android:gravity="center"android:stretchMode="columnWidth" /></LinearLayout>

detail_fragment.xml: This XML is for showing the detail in another fragment.

<?xml version="1.0" encoding="utf-8"?><ScrollViewxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="wrap_content"android:layout_height="wrap_content" ><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><ImageViewandroid:id="@+id/imageView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:layout_margin="8dp" /><TextViewandroid:id="@+id/textView"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center"android:padding="8dp" /></LinearLayout></ScrollView>

detail_act.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><ImageViewandroid:id="@+id/imageView1"android:layout_width="fill_parent"android:layout_height="fill_parent"android:src="@drawable/ic_launcher" /></LinearLayout>

Make the same XML for landscape mode and for tablets. It's working fine for me. Hope it will helpful for you.

Solution 2:

You need to define an event callback to the activity activity callback. That is, your left fragment must first notify the container activity that an event occurred (i.e. one of the list items were selected). The container activity will then pass this information to the right fragment, which will then update its UI accordingly.

I could explain this in more detail, but there are several tutorials on the internet that teach just that. I suggest you read through some of them, as the concept will make a lot more sense once you do.

Post a Comment for "How To Show Different Layouts Inside Fragments"