How do you make Custom Listview rows in baseadapter clickable? - android

I'm having a heck of a time making rows from a custom list view made with a baseadapter clickable. Currently, they can be clicked, but an error ensues and the app crashes..
ANY HELP WOULD BE APPRECIATED
Here is the main activity which includes the custom adapter that extends a baseadapter
public class MainActivity extends Activity implements OnItemClickListener {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new HalsAdapter(this));
list.setOnItemClickListener(this);
}
class SingleRow {
String title;
String description;
int image;
SingleRow(String title, String description, int image) {
this.title = title;
this.description = description;
this.image = image;
}
}
class HalsAdapter extends BaseAdapter {
ArrayList < SingleRow > list;
Context context;
HalsAdapter(Context c) {
context = c;
list = new ArrayList < SingleRow > ();
Resources res = c.getResources();
String[] titles = res.getStringArray(R.array.titles);
String[] descriptions = res.getStringArray(R.array.descriptions);
int[] images = {
R.drawable.placeholder1, R.drawable.placeholder2, R.drawable.placeholder3, R.drawable.placeholder4, R.drawable.placeholder5, R.drawable.placeholder6, R.drawable.placeholder7, R.drawable.placeholder8, R.drawable.placeholder9, R.drawable.placeholder10, R.drawable.placeholder11, R.drawable.placeholder12, R.drawable.placeholder13, R.drawable.placeholder14, R.drawable.placeholder15
};
for (int i = 0; i < 15; i++) {
list.add(new SingleRow(titles[i], descriptions[i], images[i]));
}
}
#Override
public int getCount() {
return list.size();
}#Override
public Object getItem(int i) {
return list.get(i);
}#Override
public long getItemId(int i) {
return i;
}#Override public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater inflater(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, viewGroup, false);
TextView title = (TextView) row.findViewById(R.id.textView);
TextView description = (TextView) row.findViewById(R.id.textView2);
ImageView image = (ImageView) row.findViewById(R.id.imageView);
SingleRow temp = list.get(i);
title.setText(temp.title);
description.setText(temp.description);
image.setImageResource(temp.image);
return row;
}
}#Override
public void onItemClick(AdapterView <? > arg0, View arg1, int arg2, long arg3) {
Intent intent = new Intent(homeScreen.this, privateSpaceList.class);
startActivity(intent);
break;
}
}
Here is single_row.xml
`<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:src="#drawable/placeholder1" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/imageView"
android:layout_toRightOf="#+id/imageView"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView"
android:layout_alignLeft="#+id/textView"
android:layout_alignParentRight="true"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>`
I left the onitemclick empty because my methods were not working and the mainactivity doesn't like me to call the other method of onitemclick.
I created an activity called ListItemActivity I would like the onclick to call, in turn the listitemactivity calls a test.xml page. I have been stuck for a few days trying to figure out how to make the custom rows clickable.. Any help would be greatly appreciated.

Related

Get view from ListView row

Basically all I'm trying to do is have a button appear in a row, when the row is selected. I have tried many methods, and they all seem to work including the one below...I get the ImageView but calling setVisibility() on it does nothing:
ListFragment
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
setSellButton();
}
public View getViewForPosition(int position){
int relativePos = position - listview.getFirstVisiblePosition();
if( relativePos < 0 || relativePos > listview.getChildCount()){
return null;
}
return listview.getChildAt(relativePos);
}
public void setSellButton() {
View x = getViewForPosition(Constants.lastSelection);
ImageView y = (ImageView)x.findViewById(R.id.ivSell);
y.setVisibility(View.VISIBLE);
}
No errors, and debug shows that everything is right in setSellButton() but setVisibility() never works. Is this something I can only do in the adapter? Thanks!
Edit: Row Layout XML as requested
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:orientation="horizontal"
android:gravity="center_vertical"
android:background="#drawable/thelist"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivStar"
android:src="#drawable/liststar"
android:layout_weight="1" />
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_weight="10">
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textStyle="bold">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tvValue"
android:textSize="13sp" />
</LinearLayout>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/coin"
android:id="#+id/ivSell"
android:visibility="invisible" />
</LinearLayout>
Edit: Adapter
public class InventoryAdapter extends ArrayAdapter<Integer> {
private final Context context;
private final ArrayList<String> names;
private final ArrayList<Integer> stock;
LayoutInflater inflater;
View rowView;
String stockText;
TextView textView;
TextView textView2;
ImageView iv;
public InventoryAdapter(Context context, ArrayList<String> names, ArrayList<Integer> stock) {
super(context, R.layout.inv_rowlayout, stock);
this.context = context;
this.names = names;
this.stock = stock;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.inv_rowlayout, parent, false);
String stockNumber = stock.get(position).toString();
final String name = names.get(position);
textView = (TextView) rowView.findViewById(R.id.label);
textView.setText(names.get(position));
textView2 = (TextView) rowView.findViewById(R.id.tvValue);
textView2.setText(stockNumber);
iv = (ImageView)rowView.findViewById(R.id.ivSell);
return rowView;
}
}
Well. First of all allow me to adapt your row xml. It's better to use RelativeLayout instead of LinearLayout. It's more flexible.
row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#drawable/thelist"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:minHeight="#dimen/listView_minHeight">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivStar"
android:contentDescription="#string/list_item_image_desc"
android:layout_gravity="center_vertical"
android:layout_centerVertical="true"
android:src="#drawable/liststar" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/ivStar"
android:layout_toEndOf="#+id/ivStar"
android:layout_alignParentTop="true"
android:id="#+id/label"
android:text="New Text"
android:textSize="15sp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textSize="13sp"
android:id="#+id/tvValue"
android:layout_below="#+id/label"
android:layout_toRightOf="#+id/ivStar"
android:layout_toEndOf="#+id/ivStar"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ivSell"
android:src="#drawable/coin"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="invisible" />
</RelativeLayout>
You're probably subclassing BaseAdapter. What you'll have to do is to create a method there to change the visibility of your ImageView. Then when you have your item clicked, you can get the adapter and call that method.
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private Context context_;
private ArrayList<YourDataHolder> items;
private YourDataHolder lastHolder = null;
private final String LOG_TAG = CustomAdapter.class.getSimpleName();
public CustomAdapter(Context context, ArrayList<YourDataHolder> items) {
this.context_ = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater)
context_.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.row_layout, null);
}
final TextView tv_label = (TextView) convertView.findViewById(R.id.label);
final TextView tv_value = (TextView) convertView.findViewById(R.id.tvValue);
final ImageView iv_star = (ImageView) convertView.findViewById(R.id.ivSell);
YourDataHolder holder = items.get(position);
tv_label.setText(holder.getLabel());
tv_value.setText(holder.getValue());
if (holder.isImageVisible() && iv_star.getVisibility() == ImageView.INVISIBLE) {
iv_star.setVisibility(ImageView.VISIBLE);
}
else if (iv_star.getVisibility() == ImageView.VISIBLE) {
iv_star.setVisibility(ImageView.INVISIBLE);
}
return convertView;
}
public void onItemSelect(int position) {
if (position < items.size()) {
YourDataHolder holder = items.get(position);
holder.setVisibility(true);
if (lastHolder != null) {
lastHolder.setVisibility(false);
}
lastHolder = holder;
}
}
}
Assuming you're using a data holder like this one:
YourDataHolder.java
public class YourDataHolder {
private String label;
private String value;
private boolean isVisible;
public YourDataHolder(String label, String value) {
this.label = label;
this.value = value;
isVisible = false;
}
public String getLabel() {
return label;
}
public String getValue() {
return value;
}
public boolean getVisibility() {
return isVisible;
}
public void setVisibility(boolean isVisible) {
this.isVisible = isVisible;
}
}
And then, on your onItemClick(), do the magic.
YourFragment.java
private CustomAdapter adapter;
// Rest of the Fragment. Where you create the adapter, and assign it to the ListView.
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.onItemSelect(position);
adapter.notifyDataSetChanged();
}
My guess is, that after the click on the item you need to call the notifyDataSetChanged method on the adapter. And then render the button on the selected list view item.
It is something that I would do in the adapter, having direct access to the imageview would make the process easier. I previously attempted to do it from the listview level and was unable to do to the conditions I had setup.

Data not showing in static way using listview

I am new to android and i am working on listview. I am trying to show data using listview in xml and adapter in class file. I am working on following 3 files.
First file: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.listpractice.MainActivity" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
></ListView>
</RelativeLayout>
Second file: row1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight" >
<ImageView
android:id="#+id/icon"
android:contentDescription="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/firstTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:textSize="30sp"
android:text="#string/hello_world"
/>
<TextView
android:id="#+id/secondTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:layout_below="#id/firstTextView"
android:textSize="13sp"
android:text="#string/hello_world"
/>
</RelativeLayout>
Third file: MainActivity.java
package com.listpractice;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class MainActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
My Problem : Now i want to show data of row1.xml but i don't have dynamic data. how can i show data using third(.class) file.
check out this link it will help http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
either you need to create adapter file
public class CustomBaseAdapter extends BaseAdapter{
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
//TextView txtDesc;
ImageView imgarrow;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
//holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.imgarrow=(ImageView)convertView.findViewById(R.id.arrow_icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
//holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.imgarrow.setImageResource(rowItem.getImg());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
MainActivity
public class MainActivity extends Activity implements OnItemClickListener{
public static final String[] titles = new String[] { "Krish",
"John Cena", "Kane","Roman Reigns"};
public static final Integer[] images = { R.drawable.fourth,R.drawable.second,R.drawable.first,R.drawable.third};
public static final Integer[] imagearow = {R.drawable.arrow,R.drawable.arrow,R.drawable.arrow,R.drawable.arrow };
ListView listView;
List<RowItem> rowItems;
private ImageView btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_home);
//list_travels=(ListView)findViewById(R.id.list_travels);
btn=(ImageView)findViewById(R.id.btnaddhotels);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Intent i=new Intent(HomeScreen.this,Registerhotel_resorts.class);
startActivity(i);
}
});
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i],imagearow[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list_hotels);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Intent i1=new Intent(HomeScreen.this,KrishnaParkResort.class);
startActivity(i1);
}
}
You should read this article on Building Layouts with an Adapter. It has some handy concepts which you will need to get your head around.
The fundamental concept is that you need to link your ListView to an Adapter which populates the rows and adds them to the ListView.
Looking at your row1.xml, it looks like you will need a collection of objects which contain;
An image for icon
String for firstTextView
String for secondTextView
You can build a little snippet to create an array of prepopulated objects for test purposes.
public class YourObject {
private Bitmap icon;
private String text1;
private String text2;
public YourObject(Bitmap icon, String text1, String text2) {
this.icon = icon;
this.text1 = text1;
this.text2 = text2;
}
// GETTERS AND SETTERS
}
Then create a collection of them
List<YourObject> data = new ArrayList<>();
for (int z = 0; z < 5; z++) {
YourObject yourObject = new YourObject(yourIcon, "Text1: " + z, "Text2: " + z);
data.add(yourObject);
}
Once you have this collection, you send it to a your Adapter constructor along with the reference to row1.xml, then follow the guide to populate the rows.

how to insert an image into a listview?

I would like to insert a small image to the right of each item in a listview
basically my app should do so as soon as the user clicks on an item in the list view, the image becomes visible, otherwise it must remain invisible.
below is my activity with its XML
Activity
public class EpisodiActivity extends Activity {
public class ViewModel {
private String url;
private String name;
public ViewModel(String url, String name) {
this.url = url;
this.name = name;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//creazione fullscreen activity
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.episodi_activity);
String[] episodi = getIntent().getStringArrayExtra("Product");
String[] urls = getIntent().getStringArrayExtra("urls");
ListView mylist = (ListView) findViewById(R.id.listView1);
// And in this loop we create the ViewModel instances from
// the name and url and add them all to a List
List<ViewModel> models = new ArrayList<ViewModel>();
for (int i = 0; i < episodi.length; i++) {
String name = episodi[i];
String url = "No value";
if (i < urls.length) {
url = urls[i];
}
ViewModel model = new ViewModel(url, name);
models.add(model);
}
// Here we create the ArrayAdapter and assign it to the ListView
// We pass the List of ViewModel instances into the ArrayAdapter
final ArrayAdapter<ViewModel> adapter = new ArrayAdapter<ViewModel>(this, android.R.layout.simple_list_item_1, models);
mylist.setAdapter(adapter);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
// Here we get the ViewModel at the given position
ViewModel model = (ViewModel) arg0.getItemAtPosition(position);
// And the url from the ViewModel
String url = model.getUrl();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
}
});
}
XML
RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/pubblicita"
android:cacheColorHint="#ffd700"
android:background="#drawable/sfondobottone" />
I think you want this kind of output in listview
text with image in listview
You can use custom listview . Make a class which extends BaseAdapter class
here is the exmaple that i am using
Your BaseAdapter
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FrontListBaseAdapter extends BaseAdapter {
private static ArrayList<FrontDetails> itemDetailsrrayList;
private LayoutInflater l_Inflater;
public FrontListBaseAdapter(Context context, ArrayList<FrontDetails> results) {
itemDetailsrrayList = results;
l_Inflater = LayoutInflater.from(context);
}
public int getCount() {
return itemDetailsrrayList.size();
}
public Object getItem(int position) {
return itemDetailsrrayList.get(position);
}
public long getItemId(int position) {
return position;
}
// get the views in frontview xml file where you have
// define multiple views that will appear in listview each row
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.frontview, null);
holder = new ViewHolder();
holder.Image = (ImageView) convertView.findViewById(R.id.adminpic1);
holder.MsgType = (TextView) convertView.findViewById(R.id.msgtype1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.Image.setImageResource(R.drawable.mainlogo); // you can set your setter here
holder.MsgType.setText(itemDetailsrrayList.get(position).getMsgType());
return convertView;
}
// holder view for views
static class ViewHolder {
ImageView Image;
TextView MsgType;
}
}
your FrontDetails class where you will make getters and setters and this class will be used in final ArrayList resultse = new ArrayList();
import android.graphics.Bitmap;
public class FrontDetails {
public int getImage() {
return image;
}
public void setImage(int imageN) {
this.image = imageN;
}
public String getMsgType() {
return MsgType;
}
public void setMsgType(String text) {
this.MsgType = text;
}
private int image;
private String MsgType;
}
your frontview.XML where you put your multiple views that will be in each row or your layout
<?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="100dp"
android:orientation="vertical"
android:layout_margin="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="80dp" >
<ImageView
android:id="#+id/adminpic1"
android:layout_width="60dp"
android:layout_height="60dp"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/msgtype1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="4dp"
android:textSize="1sp"
android:text="MsgType" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
and your listview in xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/sync"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sync" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp" >
</ListView>
</LinearLayout>
now in your main activity
final ArrayList<FrontDetails> resultse = new ArrayList<FrontDetails>();
FrontListBaseAdapter asdf = new FrontListBaseAdapter(context, resultse);
lv1.setAdapter(new FrontListBaseAdapter(Front.this, resultse));
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
Object o = lv1.getItemAtPosition(position);
FrontDetails obj_itemDetails = (FrontDetails)o;
Toast.makeText(context, "You have chosen " + ' ' + obj_itemDetails.getMsgType(), Toast.LENGTH_LONG).show();
}
});
EDIT:
From here i learned Custom Listview its a simple exmaple with image
http://www.javasrilankansupport.com/2012/05/android-listview-example-with-image-and.html
http://www.javacodegeeks.com/2012/10/android-listview-example-with-image-and.html
Use custom listview with BaseAdapter
Your Adapter
public class CustomBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
Your list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/icon"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="#string/image"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/icon"
android:paddingBottom="10dp"
android:textColor="#CC0033"
android:textSize="16dp" />
<TextView
android:id="#+id/desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_toRightOf="#+id/icon"
android:paddingLeft="10dp"
android:textColor="#3399FF"
android:textSize="14dp" />
</RelativeLayout>
Your Single Row item class
public class RowItem {
private int imageId;
private String title;
private String desc;
public RowItem(int imageId, String title, String desc) {
this.imageId = imageId;
this.title = title;
this.desc = desc;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title + "\n" + desc;
}
}
List view implementation
listView = (ListView) findViewById(R.id.list);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
I can give some tips ,but unfortunately couldn't help you by example..
First of all create one custom adapter(extends BaseAdapter) followed by one custom layout..
Here the custom layout contains the textview and one image view(by default invisible) at the right.
Just customize your list view with your adapter and put text inside TextView through get view()..
At last in your listItemClickListener make the image visible by its position.
You can set here on xml like this
android:visibility="visible"
or
android:visibility="invisible"
or
android:visibility="gone"
Java program:
ImageView imgView = (ImageView)findViewById(R.id.custom);
set your ImageView like this
imgView .setVisibility(View.VISIBLE);
imgView .setVisibility(View.INVISIBLE);
imgView .setVisibility(View.GONE);
Difference between INVISIBLE and GONE.
INVISIBLE - The widget will be invisible but space for the widget will be show.
GONE - Both space and widget is invisible.
Now you can hook your setOnItemClickListener()
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
imgView .setVisibility(View.VISIBLE);
}
});

Android - ListView with 2 different Colors

I have got a ListView and I want to change the Backgroundcolor of it. It should go like this. 1.Item = grey; 2. Item; white; 3. Item = grey; 4. Item = white etc. So it should have 2 backgroundcolors. I am trying to archieve that for almost 2 hours. I am getting confused. I cant get up with a Solution. I hope someone of you could help me.
I tried it with:
for(int counter = 0; counter < itemList.size(); counter++){
if( adapter.getItem(position) %2 == 1 ){
Layout.setBackgroundColor(Color.GREY)
};
else{
Layout.setBackgroundColor(Color.WHITE);
}
So here is my hole code. I hope someone of you can tell me:
MainActivity
public class MainActivity extends Activity implements OnItemClickListener {
ListView lview3;
ListViewCustomAdapter adapter;
private ArrayList<Object> itemList;
private ItemBean bean;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prepareArrayLits();
lview3 = (ListView) findViewById(R.id.listView1);
adapter = new ListViewCustomAdapter(this, itemList);
lview3.setAdapter(adapter);
lview3.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
// TODO Auto-generated method stub
RelativeLayout Layout = (RelativeLayout) findViewById(R.id.relativeLayout1);
ItemBean bean = (ItemBean) adapter.getItem(position);
for(int counter = 0; counter < itemList.size(); counter++){
adapter.getItem(position);
Layout.setBackgroundColor(Color.CYAN);}
Toast.makeText(this, "Title => "+bean.getTitle()+" \n Description => "+bean.getDescription(), Toast.LENGTH_SHORT).show();
}
/* Method used to prepare the ArrayList,
* Same way, you can also do looping and adding object into the ArrayList.
*/
public void prepareArrayLits()
{
itemList = new ArrayList<Object>();
AddObjectToList(R.drawable.ic_add, "add", "Add desc", "2");
AddObjectToList(R.drawable.ic_delete, "Delete", "Delete desc", "2");
AddObjectToList(R.drawable.ic_down, "Down", "Down desc", "2");
AddObjectToList(R.drawable.ic_info, "Information", "Information desc", "2");
AddObjectToList(R.drawable.ic_help, "Help", "Help desc", "2");
AddObjectToList(R.drawable.ic_download, "Download", "Download desc", "2");
AddObjectToList(R.drawable.ic_mail, "Mail", "Mail desc", "2");
AddObjectToList(R.drawable.ic_search, "Search", "Search desc", "2");
AddObjectToList(R.drawable.ic_settings, "Settings", "Settings desc", "2");
}
// Add one item into the Array List
public void AddObjectToList(int image, String title, String desc, String duration)
{
bean = new ItemBean();
bean.setduration(duration);
bean.setDescription(desc);
bean.setImage(image);
bean.setTitle(title);
itemList.add(bean);
}
}
ItemBean
public class ItemBean
{
String title;
String description;
int image;
String duration;
public String getTitle() {
return title;
}
public String getDuration() {
return duration;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public void setduration(String duration) {
this.duration = duration;
}
}
ListViewCustomAdapter
public class ListViewCustomAdapter extends BaseAdapter{
ArrayList<Object> itemList;
public Activity context;
public LayoutInflater inflater;
public ListViewCustomAdapter(Activity context,ArrayList<Object> itemList) {
super();
this.context = context;
this.itemList = itemList;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
// TODO Auto-generated method stub
return itemList.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
ImageView imgViewLogo;
TextView txtViewTitle;
TextView txtViewDescription;
TextView duration;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView==null)
{
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.items, null);
holder.imgViewLogo = (ImageView) convertView.findViewById(R.id.imgViewLogo);
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.txtViewTitle);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.txtViewDescription);
holder.duration = (TextView) convertView.findViewById(R.id.duration);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
ItemBean bean = (ItemBean) itemList.get(position);
holder.imgViewLogo.setImageResource(bean.getImage());
holder.txtViewTitle.setText(bean.getTitle());
holder.txtViewDescription.setText(bean.getDescription());
holder.duration.setText(bean.getDuration());
return convertView;
}
}
XML Layout:
*items*
<RelativeLayout android:id="#+id/relativeLayout1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:background="#drawable/list_selector" xmlns:android="http://schemas.android.com/apk/res/android" android:padding="5dip">
<ImageView
android:layout_width="50dip"
android:layout_height="50dip"
android:padding="3dip"
android:id="#+id/imgViewLogo"
android:src="#drawable/icon"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:background="#drawable/image_bg"
android:layout_marginRight="5dip"
android:scaleType="center"
>
</ImageView>
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imgViewLogo"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtViewTitle"
android:layout_toRightOf="#+id/imgViewLogo"
android:textColor="#040404"
android:typeface="sans"
android:textSize="20dip"
android:textStyle="bold"
android:layout_marginRight="15dp"
>
</TextView>
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtViewDescription"
android:textColor="#343434"
android:textSize="15dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/imgViewLogo"
android:layout_below="#+id/txtViewTitle"
android:layout_marginLeft="2dip"
android:layout_marginRight="15dp"
>
</TextView>
<TextView
android:id="#+id/duration"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/txtViewTitle"
android:gravity="right"
android:layout_marginRight="5dip"
android:textSize="15dip"
android:textColor="#10bcc9"
android:textStyle="bold"/>
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/arrow"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
/>
</RelativeLayout>
Layout:
*main*
<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:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
/>
</LinearLayout>
Every Tip would be helpful,
thanks.
Don't use that for loop to set the background color after the fact. Do it in your getView method of your adapter. Try this:
public View getView(int position, View convertView, ViewGroup parent) {
/* remainder is unchanged */
convertView.setBackgroundColor(position % 2 == 0 ? Color.WHITE : Color.GREY);
return convertView;
}
This is another way to change the background using selector switcher.
Using this method will preserve the hover and focus colors of the selector.
public View getView(int position, View convertView, ViewGroup parent) {
/* remainder is unchanged */
convertView.setBackgroundResource(position % 2 == 0 ? R.drawable.list_selector_first : R.drawable.list_selector_second);
return convertView;
}
You can do this easily by setting the background inside the getView function of your custom adapter.
Try this code:
if(position % 2 == 0)
convertView.setBackgroundColor(Color.GREY);
else
convertView.setBackgroundColor(Color.WHITE);
You can return different views from getView based on the passed in item position.
I believe you can do this based on the position
if (position == 0)
{
view.SetBackgroundColor(Android.Graphics.Color.gray);
}
else if (position == 1)
{
view.SetBackgroundColor(Android.Graphics.Color.white);
}
and so on depending on how many positions you have.

get data from Intent Activity and button activated in ListView

Hi thanks for reading this! Please help me.
I am trying to create a restaurant app which the display 3 buttons in the menu then click the food button which display the list of food, then customer can choose the food they want to order then send back the order back to first page. I read a lot of the article and some say use the listview.setItemsCanFocus(true) but I having problem to understand it to implement it. and some say the button listener inside the getView but when I implement my program just hang. Please help me. Thank you.
my menu :
here is my food(second) page
I am having problems:
to transfer the data back from the food.class back to my main class which is
restaurant.class
After I add the button in the list the food is not clickable(the whole row of food).
my main class(restaurant)
public class SesameRestaurant extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void foodMenu(View v){
startActivity(new Intent(SesameRestaurant.this,Food.class));
//setContentView(R.layout.foods);
}
public void drinkMenu(View v){startActivity(new Intent(SesameRestaurant.this,Drink.class));}
public void billMenu(View v){}
}
my second class (food.class)
package com.restaurant.sesame;
public class Food extends ListActivity {
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static final String[] title = new String[] {
"Cow Rib steak",
"Thai Prawn Fried Rice",
"Christmas Sensation Delight",
"Salmon Steak" };
static final String[] detail = new String[] {
"1h 37m Shipping: $10.00",
"1h 39m Shipping: Free",
"58m 6s Shipping: $10.00",
"59m 30s Shipping: $10.95" };
private Integer [] imgid = { R.drawable.food1, R.drawable.food2, R.drawable.food3, R.drawable.food4 };
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.foods);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],detail[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list, R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
Log.w("my app", "Click list Item!!!");
Toast.makeText(getApplicationContext(), "You have selected "+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
public void orderClick(View v){
}
private class RowData {
protected int mId;
protected String mTitle;
protected String mDetail;
RowData(int id,String title,String detail)
{
mId=id;
mTitle = title;
mDetail=detail;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mDetail;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
detail = holder.getdetail();
detail.setText(rowData.mDetail);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail() {
if(null == detail){
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
public void backClick(View v){
finish();
}
}
my food menu interface foods.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:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_height="wrap_content"
android:text="Back"
android:onClick="backClick"
android:layout_width="fill_parent">
</Button>
my list.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="wrap_content">
<ImageView android:id="#+id/img"
android:scaleType="centerCrop"
android:layout_width="100dp"
android:layout_height="100dp"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingLeft="10dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:id="#+id/title"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="16sp" />
<TextView
android:layout_width="fill_parent"
android:id="#+id/detail"
android:textColor="#ffffff"
android:layout_height="wrap_content"/>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quantity :"
android:textColor="#ffffff" />
<EditText
android:id="#+id/quantityInput"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_toRightOf="#id/quantity"
android:hint="1-10"
android:paddingLeft="10dp"
android:textSize="12dp" />
<Button
android:id="#+id/order"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="120dp"
android:layout_toRightOf="#id/quantity"
android:onClick="orderClick"
android:text="Order"
android:textSize="12dp" />
</RelativeLayout>
</LinearLayout>
I'm at school now so I don't have time to get a you a code snippet at all but you are going to need to use startActivityForResult() instead of just startActivity(). This will allow you to send information back to your main app upon completion of the your food activity.
Respond if you need me to find a snippet for you and I'll write one up quick once I get home in about an hour.

Categories

Resources