Tuesday, 5 March 2013

Android Listview with CheckBox and a button to get the selected option.

A Listview may be single choice or Multiple Choice.

Now i am going to show you a list of Item with Checkbox, once you will select your answer by checking the checkbox and click the bottom Button it will display all the selected answer as well as Total Amount.


Screenshots:- 1) This is first screen once you run the application
























Screenshots-2) Select your answer here.
























Screenshots:3) Final 

























Now in order to achieve plz follow foloowing steps:-

Step1) res/layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/lvMain"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" >
    </ListView>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="5dp"
        android:onClick="showResult"
        android:text="@string/get_answer" >
    </Button>

</LinearLayout>

Step2) res/layout/item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <CheckBox
        android:id="@+id/cbBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" >
    </CheckBox>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:orientation="vertical"
        android:layout_weight="1" >

        <TextView
            android:id="@+id/tvDescr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text=""
            android:textSize="20sp" >
        </TextView>

        <TextView
            android:id="@+id/tvPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:text="" >
        </TextView>
    </LinearLayout>

    <ImageView
        android:id="@+id/ivImage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher"
        android:layout_gravity="right"
        android:contentDescription="@string/app_name" >
    </ImageView>

</LinearLayout>

Step3) src/Product.java

package com.amit.listview;

public class Product {
    String name;
      int price;
      int image;
      boolean box;
     

      Product(String _describe, int _price, int _image, boolean _box) {
        name = _describe;
        price = _price;
        image = _image;
        box = _box;
      }
    }
Step4) src/ListAdapter.java

package com.amit.listview;

import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;

public class ListAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater lInflater;
    ArrayList<Product> objects;

    ListAdapter(Context context, ArrayList<Product> products) {
        ctx = context;
        objects = products;
        lInflater = (LayoutInflater) ctx
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

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

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.item, parent, false);
        }

        Product p = getProduct(position);

        ((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
        ((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
        ((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);

        CheckBox cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
        cbBuy.setOnCheckedChangeListener(myCheckChangList);
        cbBuy.setTag(position);
        cbBuy.setChecked(p.box);
        return view;
    }

    Product getProduct(int position) {
        return ((Product) getItem(position));
    }

    ArrayList<Product> getBox() {
        ArrayList<Product> box = new ArrayList<Product>();
        for (Product p : objects) {
            if (p.box)
                box.add(p);
        }
        return box;
    }

    OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            getProduct((Integer) buttonView.getTag()).box = isChecked;
        }
    };
}


Step 5) Your MainActivty.java

package com.amit.listview;

import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

    ArrayList<Product> products = new ArrayList<Product>();
    ListAdapter boxAdapter;

      /** Called when the activity is first created. */
      public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        fillData();
        boxAdapter = new ListAdapter(this, products);

        ListView lvMain = (ListView) findViewById(R.id.lvMain);
        lvMain.setAdapter(boxAdapter);
      }

      void fillData() {
        for (int i = 1; i <= 20; i++) {
          products.add(new Product("Product " + i, i * 100,
              R.drawable.ic_launcher, false));
        }
      }

      public void showResult(View v) {
        String result = "Selected Product are :";
        int totalAmount=0;
        for (Product p : boxAdapter.getBox()) {
          if (p.box){
            result += "\n" + p.name;
            totalAmount+=p.price;
          }
        }
        Toast.makeText(this, result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
      }
    }

Step6) res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">ListViewWithButton</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
     <string name="get_answer">Click to get Selected Answer</string>

</resources>

Download full source code click ListWithButton








76 comments:

  1. Hi Amit,

    Thanks for your post. This prove to be very useful for me. I am new in Android. Hope u will post related to Action Bar and Custom Action Bar before ICS also with screen shot and example.

    ReplyDelete
  2. Your most welcome Shorav... Please be in touch with my blog you will get exciting stuff..

    ReplyDelete
  3. Hi Amit,
    Thanks a lot. This is a very useful post. Could u help me connecting it with DB , please?

    ReplyDelete
  4. hey and could you tell me how would you select a check box of a row programatically.. ?

    waiting for a reply,,

    ReplyDelete
  5. how to save this check box value

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. hi, supposed i have a list of products with different names, how do i change it using your above codes?

    ReplyDelete
  8. You can do like

    Add this line

    String listOfProduct[] ={"Mobile", "Laptop","Electonic","Apparel"+"Vegitables"+"Hotels"+"Mall"};

    List list = Arrays.asList(listOfProduct);

    Change fillData() method

    void fillData() {
    for (int i = 0; i <= list.size(); i++) {
    products.add(new Product(list.get(i), i * 100,
    R.drawable.ic_launcher, false));
    }
    }

    Hope this will work for you.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  9. Hi,
    i have a question, what if i would like to change the way i interract with the list...
    like for example using a ListItemClick, how should i best be using this example,
    i have tried multiple things, but i'm not even getting close to the solution xD

    ReplyDelete
  10. Thank you amit .this code help me a lottt :)

    ReplyDelete
  11. Great What if we want to get the list from URL(Json format)

    ReplyDelete
  12. thanku amit ...this is really helpful project for everone...bt if you will count total no of selected checkbox...then it willl be more useful

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Thanks. It is really working perfectly

    ReplyDelete
  15. Sir how to set different price instead of random price
    sir plz give me suggetion

    ReplyDelete
  16. This comment has been removed by a blog administrator.

    ReplyDelete
  17. how to count number of selected checkbox ?

    ReplyDelete
  18. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Android Training in chennai

    ReplyDelete
  19. After working two hours(CheckBox in ListView) I gave up and searched internet for the solution and stopped at your blog, tried your code and it worked fine.
    Thanks a lot, Amit.

    ReplyDelete
  20. Wow, I have been surfing the internet for the past two hours but I have not come across such a website. It has good content that is both educative and informative post. I have gained in depth knowledge on how to use in web application development. For interesting, accurate, and SEO optimized blog articles, feel free to hire our Qualitative Dissertation Writers.

    ReplyDelete
  21. I simply want to say I’m very new to blogs and actually loved you’re blog site. Almost certainly I’m going to bookmark your blog post . You absolutely come with great well written articles. Thanks a lot for sharing your blog.

    Android training in chennai with placement | Android Training in chennai |Android Training in Velachery

    ReplyDelete
  22. I use your code and add alertdialog , i can not see aletdialg value, i have a link my file here https://www.dropbox.com/sh/kbkgl5a10lz2kzf/AADwVn6CC4PRdjSz76l2DkYva?dl=0
    How do i get a value of alert dialog.message show only list view value

    ReplyDelete
  23. How to uncheck of checkbox when click Restart button ?

    ReplyDelete
  24. Really cool post, highly informative and professionally written and I am glad to be a visitor of this perfect blog, thank you for this rare info!

    Android Online Training

    ReplyDelete
  25. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    Selenium Training in Chennai | Cloud Computing Training in Chennai

    ReplyDelete
  26. How can i get the checked item in next activity
    Thanks
    Reply me at s.g.sivanesh@gmail.com

    ReplyDelete
  27. I get the following error: "List adapter is abstract; cannot be instantiated." on the MainActivity Java Class.

    This looks like it could be a great example with some slight tweaking.

    ReplyDelete
  28. Dear sir
    I have spinner for get quantity and multiply by product price .
    So how to solve this .

    ReplyDelete
  29. I get price and total amount
    But I can't get quantity * product price

    ReplyDelete
  30. plz reply me its urgent sir...

    ReplyDelete
  31. And is this also possible with a search function to find the products?

    ReplyDelete
  32. Thank you for taking time to provide us some of the useful and exclusive information with us.
    Regards,
    selenium course in chennai

    ReplyDelete
  33. That’s a great blog!.

    For VoIP Dialers, Android and iOS chat development, Web based chat, WebRTC development, Digital Marketing and Social Media just try visiting our site!

    Software Development Company
    VoIP Dialer Development

    ReplyDelete
  34. dai yen da delete panninaga ennoda comments ya kenakooothkala

    ReplyDelete
  35. Chúc bạn luôn hạnh phúc và may mắn. Hy vọng bạn sẽ có nhiều bài viết hay hơn.

    lưới chống chuột

    cửa lưới dạng xếp

    cửa lưới tự cuốn

    cửa lưới chống muỗi

    ReplyDelete
  36. <a href="https://vidmate.vin/

    ReplyDelete
  37. Wow! Such an amazing blog. Having troubles with your assignments? Looking for assistance in your writings? Well we got it all just go to nursing essay writing service .

    ReplyDelete
  38. Thank you for the Information was so useful. Visit write my economics paper and get your online help.

    ReplyDelete
  39. Your articles really impressed for me,because of all information so nice.sap tm training in bangalore

    ReplyDelete
  40. Android users can get important hints from this post. Android users can solve their issues after reading this post. By: Master dissertation writing service.

    ReplyDelete
  41. Really very happy to say, your post is very interesting to read. I never stop myself to say something about it.You’re doing a great job. Keep it up...

    Upgrade your career Learn AWS Training from industry experts get Complete hands-on Training, Interview preparation, and Job Assistance at Bangalore Training Academy Located in BTM Layout.

    ReplyDelete
  42. Such a great information for blogger i am a professional blogger thanks…

    Upgrade your career Learn SharePoint Developer Training in Bangalore from industry experts get Complete hands-on Training, Interview preparation, and Job Assistance at Softgen Infotech.

    ReplyDelete
  43. Nice read! Thanks for sharing. Get reliable assignment help with Free Turnitin, Partial Payment, and Unlimited Revisions by a team of highly professional and experienced expert experts.

    ReplyDelete
  44. Card màn hình cũ là một trong những linh kiện không thể thiếu của một máy tính để bàn trọn bộ. Một màn hình máy tính có kèm theo bộ card màn hình cũ sẽ giúp cho máy tính để bàn cho ra hình ảnh sắc nét hơn. Tuy nhiên card màn hình cũ cũng giống như hầu hết các linh kiện máy tính chúng đều cần vệ sinh định kỳ và sử dụng đúng cách.

    Thông tin bài viết này chúng tôi sẽ chia sẻ tới bạn cách vệ sinh card màn hình cũ của máy tính để bàn. Mời bạn tham khảo để có thông tin cho mình nhé

    Hướng dẫn cách vệ sinh card màn hình cũ của máy tính để bàn

    ReplyDelete
  45. Van bướm gang đĩa inox tay quay là thiết bị, được sử dụng sử dụng để đóng mở hoặc điều tiết dòng chảy trong hệ thống đường ống, có đường kính lớn. Loại van này, tương tự như một van bi. Đĩa van được đặt chính giữa đường ống. Đĩa kết nối với thiết bị truyền động bên ngoài ( tay quay ) thông qua một thanh trục bằng kim loại. Khi xoay vô lăng ( tay quay ) thì đĩa van vận động tuy vậy song hoặc vuông góc với dòng chảy tương ứng với việc đóng mở đường ống.

    ReplyDelete
  46. Nice Blog!
    Facing error while using QuickBooks get instant solution with our QuickBooks experts.Dial +1-855-533-6333 QuickBooks Enterprise Support Phone Number

    ReplyDelete
  47. Really Nice Information It's Very Helpful All courses Checkout Here.
    Sharepoint Developer training in bangalore

    ReplyDelete
  48. Microsoft Office Suite 2007 Service Pack 3 1.0 for Windows. Fast downloads of the latest free software! Click now.. MS Office 2007 Crack Download

    ReplyDelete
  49. The improved contour of the movie project and that as well in a issue of secs. The great point about this application is that most typical yet well-liked video setups and information Download Handbrake Full Version Free

    ReplyDelete
  50. This comment has been removed by the author.

    ReplyDelete