ListView or GridView dynamically based on Phone/Tablet in Android

    Sometimes, we would like our application displays content diffirently on deferrent devices, this is supporting multiple screens topic - usally seen is mobile developement. In Android, with the layout resource folders (res/layout, res/layout-large,...) we can build suitable interfaces for various devices with different screen sizes. Back to this problems, in the same screen, we can display it by a ListView in handsets but by GridView in tablets.
    Through this tip, I'll present the way to make this trick, after complete it, our own applications will seem smoother and better adapted to each type of device.
DEMO VIDEO:

Designing layouts

    Like as note above, the most important work is create layout for each devices. In this project, design handsets layouts in res/layout folder and tablet's in res/layout-large. So, main Activity will contains a ListView or GridView depending on the situation:    Next, we also set layout for each ListView/GridView item:
   As you can see, the root layouts must include the same children views (ImageView and TextView in this case), it maybe different about root and other non-id views. With this design, after running program in phone/tablet, we will see effect!

Programmatically coding

   Reference to developer docs, ListView & GridView are both descendants of AbsListView. So, in our Activity code, refer to an instance of AbsListView:
AbsListView absListView = (AbsListView)findViewById(R.id.list_item);
   Set dummy data for ListView adapter, locate all views, we have full simple code for main Activity:
package devexchanges.info.gridviewistview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private AbsListView absListView;
    private ArrayAdapter<AsiaCountry> adapter;
    private ArrayList<AsiaCountry> countryArrayList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        absListView = (AbsListView)findViewById(R.id.list_item);
        settingData();

        adapter = new AbsListViewAdapter(this, R.layout.item_abslistview, countryArrayList);
        absListView.setAdapter(adapter);
    }

    private void settingData() {
        countryArrayList = new ArrayList<>();

        countryArrayList.add(new AsiaCountry(R.mipmap.vietnam, "Vietnam", "Việt Nam"));
        countryArrayList.add(new AsiaCountry(R.mipmap.afghanistan, "Afghanistan", "Áp-ga-nix-tan"));
        countryArrayList.add(new AsiaCountry(R.mipmap.brunei, "Brunei", "Bru-nây"));
        countryArrayList.add(new AsiaCountry(R.mipmap.cambodia, "Cambodia", "Cam-pu-chia"));
        countryArrayList.add(new AsiaCountry(R.mipmap.china, "China", "Trung Quốc"));
        countryArrayList.add(new AsiaCountry(R.mipmap.india, "India", "Ấn Độ"));
        countryArrayList.add(new AsiaCountry(R.mipmap.indonesia, "Indonesia", "In-đô-nê-xi-a"));
        countryArrayList.add(new AsiaCountry(R.mipmap.iran, "Iran", "I-ran"));
        countryArrayList.add(new AsiaCountry(R.mipmap.japan, "Japan", "Nhật Bản"));
        countryArrayList.add(new AsiaCountry(R.mipmap.laos, "Laos", "Lào"));
        countryArrayList.add(new AsiaCountry(R.mipmap.north_korea, "North Korea", "Triều Tiên"));
        countryArrayList.add(new AsiaCountry(R.mipmap.singapore, "Singapore", "Singapore"));
        countryArrayList.add(new AsiaCountry(R.mipmap.south_korea, "South Korea", "Hàn Quốc"));
        countryArrayList.add(new AsiaCountry(R.mipmap.taiwan, "Taiwan", "Đài Loan"));
        countryArrayList.add(new AsiaCountry(R.mipmap.thailand, "Thailand", "Thái Lan"));
    }
}
    Like the normal ListView/GridView adapter, we extend it from ArrayAdapter or BaseAdapter. In this, I provide a ViewHolder class to get scroll smoother and showing a Dialog when each AbsListView item was clicked:
package devexchanges.info.gridviewistview;

import android.app.Activity;
import android.app.Dialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class AbsListViewAdapter extends ArrayAdapter<Asiacountry> {

    private Activity activity;
    private List<AsiaCountry> countries;

    public AbsListViewAdapter(Activity context, int resource, List<AsiaCountry> objects) {
        super(context, resource, objects);
        this.activity = context;
        this.countries = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
            convertView = inflater.inflate(R.layout.item_abslistview, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }

        holder.flag.setImageResource(getItem(position).getFlagResource());
        holder.countryName.setText(getItem(position).getName());

        convertView.setOnClickListener(onClickListener(getItem(position), String.valueOf(position + 1)));

        return convertView;
    }

    private View.OnClickListener onClickListener(final AsiaCountry country, final String pos) {
        return new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                final Dialog dialog = new Dialog(activity);
                dialog.setContentView(R.layout.layout_dialog);
                dialog.setTitle("Selected Country");

                TextView name = (TextView) dialog.findViewById(R.id.country_name);
                TextView position = (TextView) dialog.findViewById(R.id.pos);
                TextView viName = (TextView) dialog.findViewById(R.id.vi_name);
                ImageView image = (ImageView) dialog.findViewById(R.id.image);

                name.setText(country.getName());
                viName.setText(country.getVietnameseName());
                position.setText(pos);
                image.setImageResource(country.getFlagResource());

                dialog.show();
            }
        };
    }

    private static class ViewHolder {
        private ImageView flag;
        private TextView countryName;

        public ViewHolder(View v) {
            flag = (ImageView) v.findViewById(R.id.flag);
            countryName = (TextView) v.findViewById(R.id.country_name);
        }
    }
}

Running Program

    If you use handset device, after running, a ListView will be shown:
 
And when each ListView row clicked, a Dialog with Country details will be display:
 
In Tablet, the AbsListView will be come to a GridView:
    In Android Lollipop, the Dialog can be a little difference:

Some necessary files

    This is POJO (model) of this project:
package devexchanges.info.gridviewistview;

public class AsiaCountry {

    private String name;
    private int flagResource;
    private String vietnameseName;

    public AsiaCountry (int image, String name, String viName) {
        this.flagResource = image;
        this.name = name;
        this.vietnameseName = viName;
    }

    public int getFlagResource() {
        return flagResource;
    }

    public String getVietnameseName() {
        return vietnameseName;
    }

    public String getName() {
        return name;
    }
}
    Strings resource:

Conclusions

    Through this tip, I have present a solution to "changing interface" base on user device, namely the ListView and GridView display, hope you like it. Now, you can see my project on @Github. Subcribes my site to get more tutorials!


Share


Previous post
« Prev Post
Next post
Next Post »