Monday 10 September 2012

Multiple Views in Sinlge List with ListView and Other Control - Hotel Menu Example

In this Code We will use multiple Views in a single list as well as put a Button below the list which use to show how many items will be selected in another new Activities.



  1. First We will create the layout of each row as follows layout/rowlayout.xml.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    	android:orientation="horizontal" android:layout_width="fill_parent"
    	android:layout_height="fill_parent">
    	
    	<ImageView android:layout_height="60px" 
    		android:id="@+id/imageView1"
    		android:layout_width="60px" 
    		android:src="@drawable/icon" 
    		android:maxWidth="5px"
    		android:minWidth="5px"
    		/>
    	<TextView android:text="TextView" 
    		android:layout_width="200dp"
    		android:layout_height="wrap_content" 
    		android:id="@+id/textView1"
    		android:lines="2"
    		android:layout_marginLeft="10px"
    		android:layout_marginTop="10px" 
    		android:textSize="15px"
    		></TextView>
    	<CheckBox android:text="" 
    	android:id="@+id/checkBox1" 
    	android:layout_width="wrap_content" 
    	android:layout_height="wrap_content" />
    	
    </LinearLayout>
    
  2. Than we create our main layout as follows layout/main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <ListView 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:id="@android:id/list"
        />
      <Button android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/btnOrder" 
        android:text="Order" 
        android:layout_gravity="center"/>
    </LinearLayout>
    
    Here the name of the listView must be as aboves : "@android:id/list" where android list will be automatically placed when we add the adapter in our activity class.
  3. Then we create a class which extend the ArrayAdapter  class as follows.
     
    package com.container;
    
    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    import com.container.R;
    
    public class HotelMenuAdapter extends ArrayAdapter<String> {
    	Context context;
    	String[] values;
    	int position;
    	boolean itemSelected[] = { false, false, false, false, false, false };
    
    	public HotelMenuAdapter(Context context, String[] values) {
    		super(context, R.layout.rowlayout, values);
    		this.context = context;
    		this.values = values;
    	}
    
    	public View getView(final int positon, View convertView, ViewGroup parent) {
    		LayoutInflater inflater = (LayoutInflater) context
    				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    		View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
    
    		TextView textView = (TextView) rowView.findViewById(R.id.textView1);
    		ImageView image = (ImageView) rowView.findViewById(R.id.imageView1);
    		final CheckBox checkBox = (CheckBox) rowView
    				.findViewById(R.id.checkBox1);
    
    		image.setOnClickListener(new View.OnClickListener() {
    
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				// Toast.makeText(context, ((TextView)v).getText().toString(),
    				// 5).show();
    				if (checkBox.isChecked()) {
    					checkBox.setChecked(false);
    					itemSelected[positon] = false;
    				} else {
    					checkBox.setChecked(true);
    					itemSelected[positon] = true;
    				}
    			}
    		});
    
    		textView.setOnClickListener(new View.OnClickListener() {
    
    			public void onClick(View v) {
    				// TODO Auto-generated method stub
    				// Toast.makeText(context, ((TextView)v).getText().toString(),
    				// 5).show();
    				if (checkBox.isChecked()) {
    					checkBox.setChecked(false);
    					itemSelected[positon] = false;
    				} else {
    					checkBox.setChecked(true);
    					itemSelected[positon] = true;
    				}
    			}
    		});
    
    		checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
    			public void onCheckedChanged(CompoundButton buttonView,
    					boolean isChecked) {
    				// TODO Auto-generated method stub
    				// Toast.makeText(context, String.valueOf(positon), 5).show();
    				if (isChecked) {
    					itemSelected[positon] = true;
    					// Toast.makeText(context, "Checked", 5).show();
    				} else {
    
    					itemSelected[positon] = false;
    					// Toast.makeText(context, "Not Checked", 5).show();
    				}
    
    			}
    		});
    
    		textView.setText(values[positon]);
    		switch (positon) {
    		case 0:
    			image.setImageResource(R.drawable.a);
    			break;
    		case 1:
    			image.setImageResource(R.drawable.b);
    			break;
    		case 2:
    			image.setImageResource(R.drawable.c);
    			break;
    		case 3:
    			image.setImageResource(R.drawable.d);
    			break;
    		case 4:
    			image.setImageResource(R.drawable.e);
    			break;
    		case 5:
    			image.setImageResource(R.drawable.f);
    			break;
    		case 6:
    			image.setImageResource(R.drawable.g);
    			break;
    
    		}
    
    		checkBox.setChecked(false);
    		return rowView;
    	}
    
    	public boolean[] getItemSelected() {
    		return itemSelected;
    	}
    
    	public void setItemSelected(boolean[] itemSelected) {
    		this.itemSelected = itemSelected;
    	}
    
    }
    
    In this class we also add the listeners for the ImageView, TextView as well as CheckBoxes.

  4. Then in our main Activity class we will extends the ListActivity class as follows.

    package com.container;
    
    import android.app.ListActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.CheckBox;
    import android.widget.Toast;
    
    public class HotelMenuDemoActivity extends ListActivity {
    	/** Called when the activity is first created. */
    	String[] values = { "McVeggie~Rs.40-50", "McAloo Tikki~Rs 20–50",
    			"Paneer Salsa~Rs 20–50", "Crispy Chinese~Rs 20–50",
    			"McCurry Pan~Rs 20–50", "Chicken Maharaja Mac", };
    	Button btnOrder;
    	CheckBox chBox;
    	HotelMenuAdapter menuAdapter;
    
    	
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.main);
    		
    		menuAdapter = new HotelMenuAdapter(getApplicationContext(), values);
    		setListAdapter(menuAdapter);
    
    		btnOrder = (Button) findViewById(R.id.btnOrder);
    		btnOrder.setOnClickListener(new View.OnClickListener() {
    
    			public void onClick(View arg0) {
    				// TODO Auto-generated method stub
    				boolean [] selectedItem=menuAdapter.getItemSelected();
    				int count=0;
    				Intent intent=new Intent(getApplicationContext(),ShowOrderActivity.class);
    				for(int i=0;i<selectedItem.length;i++){
    					if(selectedItem[i]==true){
    						count++;
    						intent.putExtra("items",values);
    						intent.putExtra("selected",selectedItem);
    				//	Toast.makeText(getApplicationContext(), menuAdapter.getItem(i),5).show();
    					}
    				}
    				startActivity(intent);
    			}
    		});
    
    	}
    }


  5. Finally We will create the another activity which just show the items witch is selected. as follows. 

    package com.container;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.widget.TextView;
    
    public class ShowOrderActivity extends Activity {
    
    	/** Called when the activity is first created. */
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    
    		TextView tv = new TextView(this);
    		tv.setMaxLines(10);
    		Bundle b = getIntent().getExtras();
    		String order = "Your Order is : \n";
    		String[] values = (String[]) b.getSerializable("items");
    		boolean[] items = (boolean[]) b.getSerializable("selected");
    		if (items != null && values != null) {
    			for (int i = 0; i < values.length; i++) {
    				if (items[i] == true)
    					order += values[i] + ",\n";
    			}
    		}
    		tv.setText(order);
    		setContentView(tv);
    		// TODO Auto-generated method stub
    	}
    
    }
    
That's the code:
  • When you click on the ImageView,TextView or Checkbox  corresponding Checkbox will be checked or unchecked in reverse state.  as follows

  • After selecting which ever items you want click on "Order" Button than following  output will be displayed. 

20 comments:

  1. I love this simple tutorial, but i have an error in this two lines:

    menuAdapter = new HotelMenuAdapter(getApplicationContext(), values);
    setListAdapter(menuAdapter);

    getApplicationContext() and setListAdapter ""Cannot resolve symbol""

    ReplyDelete
  2. Hi! Can you give me more details on some freelancing sites that will help me make money? I am a housewife and am looking for some place where I can post my jobs without leaving my home. I worked as a web developer before becoming a stay-at-home mom. Will I get job offers as a freelancer? Your blog was very useful. I checked out www.gricree.com, www.zopthemes.com and www.peopleperhour.com sites. They come with high ratings and good reviews. Let me give a try. What do you say?

    ReplyDelete
  3. i like your post what about i add dialogbox to check more i try it do not work my file like is here please answer mesfun@hotmail.com
    my file link is here https://www.dropbox.com/sh/kbkgl5a10lz2kzf/AADwVn6CC4PRdjSz76l2DkYva?dl=0

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

    ReplyDelete
  5. Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.

    rpa training in Chennai | rpa training in pune

    rpa online training | rpa training in bangalore

    ReplyDelete
  6. I would assume that we use more than the eyes to gauge a person's feelings. Mouth. Body language. Even voice. You could at least have given us a face in this test.
    Data Science course in rajaji nagar | Data Science with Python course in chenni
    Data Science course in electronic city | Data Science course in USA
    Data science course in pune | Data science course in kalyan nagar

    ReplyDelete
  7. This is such a good post. One of the best posts that I\'ve read in my whole life. I am so happy that you chose this day to give me this. Please, continue to give me such valuable posts. Cheers!
    java training in omr | oracle training in chennai

    java training in annanagar | java training in chennai

    ReplyDelete
  8. This is most informative and also this post most user friendly and super navigation to all posts... Thank you so much for giving this information to me.. 
    Devops training in marathahalli
    Devops training in rajajinagar

    ReplyDelete
  9. Your content is excellent but with pics and videos,
    this blog could certainly be one of the best in its field.
    Excellent blog!
    kajal hot

    ReplyDelete
  10. Thanks Admin for sharing such a useful post, I hope it’s useful to many individuals for developing their skill to get good career.


    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  11. Thanks! Very interesting to read. This is really very helpful. Data Science Course in Jaipur

    ReplyDelete