Wednesday, 30 December 2015

TableLayout like ListView (Multi Column ListView)

Many Android developers mess up in building a Multi column ListView, which looks similar to a table layout in android.
So in this tutorial I am showing you how to create a multi column list view.

Output : 



Step 1 : Create a new project by going to File ⇒ New Android Application Project. Fill all the details and name your activity as MainActivity. (eclipse)

Step 2 : Design the activity_main.xml layout for MainActivity under layout folder as shown below

 activity_main.xml
 
    <LinearLayout
        android:id = "@+id/relativeLayout1"
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:background = "@color/colorCell" >

        <TextView
            android:layout_width = "0dp"
            android:layout_height = "wrap_content"
            android:layout_weight = "1"
            android:gravity = "center"
            android:padding = "5dp"
            android:text = "@string/sNo"
            android:textColor = "#ffffff" />

        <TextView
            android:layout_width = "0dp"
            android:layout_height = "wrap_content"
            android:layout_weight = "2"
            android:gravity = "center"
            android:padding = "5dp"
            android:text = "@string/product"
            android:textColor = "#ffffff"/ >

        <TextView
            android:layout_width = "0dp"
            android:layout_height = "wrap_content"
            android:layout_weight = "1.5"
            android:gravity = "center"
            android:padding = "5dp"
            android:text = "@string/category"
            android:textColor = "#ffffff" />

        <TextView
            android:layout_width = "0dp"
            android:layout_height = "wrap_content"
            android:layout_weight = "1"
            android:gravity = "center"
            android:padding = "5dp"
            android:text = "@string/price"
            android:textColor = "#ffffff" />
    </LinearLayout>

    <ListView
        android:id = "@+id/listview"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:divider = "@null"/>

Step 3 : Create a xml file under drawable-hdpi and name it as cell_shape.xml as shown below.

  cell_shape.xml

 <layer-list xmlns:android = "http://schemas.android.com/apk/res/android">

    <item
        android:left = "-2dp"
        android:top = "-2dp">
        <shape android:shape = "rectangle" >
            <solid android:color = "@android:color/transparent" />

            <stroke
                android:width = "1dp"
                android:color = "@color/colorCell" />
        </shape>
    </item>
</layer-list

Step 4 : Create a new class under src/package. Right Click on src/package (com.example.multicolumnlistview) ⇒ New ⇒ Class and name it as Model.java and fill it with following code.

Model.java

public class Model {

    private String sNo;
    private String product;
    private String category;
    private String price;

    public Model(String sNo, String product, String category, String price) {
        this.sNo = sNo;
        this.product = product;
        this.category = category;
        this.price = price;
    }

    public String getsNo() {
        return sNo;
    }

    public String getProduct() {
        return product;
    }

    public String getCategory() {
        return category;
    }

    public String getPrice() {
        return price;
    }
}

Step 5 : Create a new xml file under res/layout. Right Click on res/layout ⇒ New ⇒ Android XML File and name it as listview_row.xml and fill it with following code. This layout is the custom layout inside list adapter.

listview_row.xml 
 
    <LinearLayout
        android:id = "@+id/relativeLayout1"
        android:layout_width = "fill_parent"
        android:layout_height = "wrap_content"
        android:background = "@color/colorCell" >

        <TextView       
            android:id = "@+id/sNo"      
            android:layout_width = "0dp"
            android:layout_height = "match_parent"
            android:layout_weight = "1"
            android:background = "@drawable/cell_shape"
            android:ellipsize = "end"
            android:padding = "5dp"
            android:text = "@string/sNo"
            android:singleLine = "true" />

        <TextView       
            android:id = "@+id/product"      
            android:layout_width = "0dp"
            android:layout_height = "match_parent"
            android:layout_weight = "2"
            android:background = "@drawable/cell_shape"
            android:ellipsize = "end"
            android:padding = "5dp"
            android:text = "@string/product"
            android:singleLine = "true" />

        <TextView       
            android:id = "@+id/category"      
            android:layout_width = "0dp"
            android:layout_height = "match_parent"
            android:layout_weight = "1.5"
            android:background = "@drawable/cell_shape"
            android:ellipsize = "end"
            android:padding = "5dp"
            android:text = "@string/category"
            android:singleLine = "true" />

         <TextView       
            android:id = "@+id/price"      
            android:layout_width = "0dp"
            android:layout_height = "match_parent"
            android:layout_weight = "1"
            android:background = "@drawable/cell_shape"
            android:ellipsize = "end"
            android:padding = "5dp"
            android:text = "@string/price"
            android:singleLine = "true" />
    </LinearLayout>

 Creating custom adapter for list view : 
Step 6 : Create a new class under src/package. Right Click on src/package (com.example.multicolumnlistview) ⇒ New ⇒ Class and name it as listviewAdapter.java and fill it with following code.


listviewAdapter.java

public class listviewAdapter extends BaseAdapter {

     public ArrayList<Model> productList;
     Activity activity;

    public listviewAdapter(Activity activity, ArrayList<Model> productList) {
        super();
        this.activity = activity;
        this.productList = productList;
    }

    @Override
    public int getCount() {
        return productList.size();
    }

    @Override
    public Object getItem(int position) {
       return productList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    private class ViewHolder {
        TextView mSNo;
        TextView mProduct;
        TextView mCategory;
        TextView mPrice;
    }

    @Override
     public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;
        LayoutInflater inflater = activity.getLayoutInflater();

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.listview_row, null);
            holder = new ViewHolder();
            holder.mSNo = (TextView) convertView.findViewById(R.id.sNo);
            holder.mProduct = (TextView) convertView.findViewById(R.id.product);
            holder.mCategory = (TextView) convertView
                    .findViewById(R.id.category);
            holder.mPrice = (TextView) convertView.findViewById(R.id.price);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Model item = productList.get(position);
        holder.mSNo.setText(item.getsNo().toString());
        holder.mProduct.setText(item.getProduct().toString());
        holder.mCategory.setText(item.getCategory().toString());
        holder.mPrice.setText(item.getPrice().toString());

        return convertView;
    }
}

 Step 7 : Add the following code in MainActivity.

MainActivity.java

    private ArrayList<Model> productList;

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

        productList = new ArrayList<Model>();
        ListView lview = (ListView) findViewById(R.id.listview);
        listviewAdapter adapter = new listviewAdapter(this, productList);
        lview.setAdapter(adapter);

        populateList();

        adapter.notifyDataSetChanged();
       
        lview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

                String sno = ((TextView)view.findViewById(R.id.sNo)).getText().toString();
                String product = ((TextView)view.findViewById(R.id.product)).getText().toString();
                String category = ((TextView)view.findViewById(R.id.category)).getText().toString();
                String price = ((TextView)view.findViewById(R.id.price)).getText().toString();
               
                Toast.makeText(getApplicationContext(),
                          "S no : " + sno +"\n"
                        +"Product : " + product +"\n"
                        +"Category : " +category +"\n"
                        +"Price : " +price, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void populateList() {

        Model item1, item2, item3, item4, item5;

        item1 = new Model("1", "Apple (Northern Spy)", "Fruits", "₹. 200");
        productList.add(item1);

        item2 = new Model("2", "Orange (Sunkist navel)", "Fruits", "₹. 100");
        productList.add(item2);

        item3 = new Model("3", "Tomato", "Vegetable", "₹. 50");
        productList.add(item3);

        item4 = new Model("4", "Carrot", "Vegetable", "₹. 80");
        productList.add(item4);

        item5 = new Model("5", "Banana (Cavendish)", "Fruits", "₹. 100");
        productList.add(item5);
    }

Checkout the live demo :



Source code : Click here to download. 

Source link

As always, Thanks a lot for reading...

Don't forget to share this post if you found it interesting!
If you find something to add to this post? or any other quick thoughts/hints that you think people will find useful? Share it in the comments & feedback's are most welcome. 

17 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This post is much helpful for us. This is really very massive value to all the readers and it will be the only reason for the post to get popular with great authority.
    Android online training hyderabad .

    ReplyDelete
  3. The article is actually the best topic on this. I fit in with your conclusions and will eagerly look forward to your next updates.For information regarding us please visit our App Development Company in Indore.

    ReplyDelete
  4. Short courses and training are a great way to learn and advance in career and I think more people should move towards it

    ReplyDelete
  5. One of the knowledge stuffed blogs i've ever seen. It helps revamp existing technology and architecture, using constantly evolving strategies to drive improved market performance. reffer the given blog for more info Application Modernization Services or
    reach +18882075969 for more information

    ReplyDelete
  6. Nice information about android app development.thanks for sharing this information

    ReplyDelete
  7. Android software development is the process of creating apps for devices that run the Android operating system. Using the Android software development kit, Google claims that Android app development may be created in Kotlin, Java, and C++ languages," however additional languages are also feasible.

    ReplyDelete
  8. Hello, This is a very good Article and informative. Here if you find any loan app developer you can connect us.

    ReplyDelete
  9. https://androidcontrol.blogspot.com/2016/12/android-things-raspberry-pi.html?sc=1702488026156#c4374194828333505462

    ReplyDelete
  10. Thank you for sharing this. This will help to many android developers and app development company to create table layout in android.

    ReplyDelete
  11. The article is actually the best topic on this. Thanks very nice blog! Useful information Thanks For Sharing For More Details About Ewallet App Development

    ReplyDelete