Update custom gridview from custom list adapter android - android

I have a listview that contains a set of a custom view. Inside each custom view is a gridview.
I want to be able to update the background of each cell in the gridview when the user clicks a checkbox in the custom view.
Here is my custom view
<?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="wrap_content"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp" >
<TextView
android:id="#+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="32sp" />
<CheckBox
android:id="#+id/lblHeaderCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:focusable="false"
android:layout_centerVertical="true" />
</RelativeLayout>
<ca.package.CustomGridView
android:id="#+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:clickable="false"
android:gravity="center"
android:numColumns="7"
android:padding="10dp"
android:stretchMode="columnWidth"
clickable="true" />
Here is my layout for each grid cell
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:clickable="true" >
<TextView
android:id="#+id/grid_itemTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center">
</TextView>
</LinearLayout>
Here is how I fill the list
expListView = (ListView) this.findViewById(R.id.event_list);
prepareListData();
listAdapter = new CustomAdapter(this, listDataHeader,
listDataChild, listChildBoolean);
expListView.setAdapter(listAdapter);
Here is the getView method in my custom adapter for the listView
public View getView(int groupPosition, View convertView, ViewGroup parent) {
final int gp = groupPosition;
String headerTitle = (String) getGroup(groupPosition);
// Boolean bool = _listDataBoolean.get(groupPosition);
Boolean bool = currentCalendarEvents.get(groupPosition).getAlert();
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.list_group, null);
}
String[] data = new String[14];
List<String> times = _currentListDataChild.get(_currentListDataHeader
.get(groupPosition));
data[0] = "Su";
data[1] = "M";
data[2] = "Tu";
data[3] = "W";
data[4] = "Th";
data[5] = "F";
data[6] = "Sa";
data[7] = times.get(6); // sun
data[8] = times.get(0); // mon
data[9] = times.get(1); // tues
data[10] = times.get(2); // wed
data[11] = times.get(3); // thurs
data[12] = times.get(4); // fri
data[13] = times.get(5); // sat
ArrayList<Boolean> boolArray = _listChildBoolean.get(_currentListDataHeader
.get(groupPosition));
final GridView gridView = (GridView) convertView.findViewById(R.id.gridView);
final GridAdapter adapter = new GridAdapter(this._context, data, boolArray);
gridView.setAdapter(adapter);
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.lblListHeader);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
final CheckBox chk2 = (CheckBox) convertView
.findViewById(R.id.lblHeaderCheckbox);
chk2.setChecked(bool);
chk2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (chk2.isChecked()) {
currentCalendarEvents.get(gp).setAlert(true);
currentCalendarEvents.get(gp).setDaysTrue();
// I WANT TO UPDATE THE LIST HERE
Log.i(LOG_TAG, "box checked");
} else {
currentCalendarEvents.get(gp).setAlert(false);
currentCalendarEvents.get(gp).setDaysFalse();
// AND HERE
Log.i(LOG_TAG, "box not checked");
}
}
});
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.i(LOG_TAG, "gridview clicked");
currentCalendarEvents.get(gp).setBoolDays(adapter.getHashMap());
}
});
return convertView;
}
Here is my GridAdapter
public class GridAdapter extends BaseAdapter {
private Context context;
private String[] items;
private ArrayList<Boolean> boolArray;
private ArrayList<View> views;
LayoutInflater inflater;
public GridAdapter(Context context, String[] items,
ArrayList<Boolean> boolArray) {
this.context = context;
this.items = items;
this.boolArray = boolArray;
this.views = new ArrayList<View>();
inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.grid_cell, null);
final TextView tv = (TextView) convertView
.findViewById(R.id.grid_itemTxt);
tv.setText(items[position]);
if (position < 7) {
convertView.setBackgroundColor(Color.DKGRAY);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
tv.setTextColor(Color.WHITE);
tv.setTypeface(null, Typeface.BOLD);
tv.setLines(2);
} else {
Log.e("blerp", "test : " + items[position]);
if (!items[position].equals("")) {
if (boolArray.get(position % 7)) {
convertView.setBackgroundColor(context.getResources()
.getColor(R.color.LightGreen));
} else {
convertView.setBackgroundColor(Color.LTGRAY);
}
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolArray.get(position % 7)) {
((View) tv.getParent())
.setBackgroundColor(Color.LTGRAY);
boolArray.set(position % 7, false);
} else {
((View) tv.getParent())
.setBackgroundColor(context
.getResources().getColor(
R.color.LightGreen));
boolArray.set(position % 7, true);
}
}
});
} else
convertView.setBackgroundColor(Color.LTGRAY);
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
tv.setLines(2);
}
}
return convertView;
}
#Override
public int getCount() {
return items.length;
}
#Override
public Object getItem(int position) {
return items[position];
}
#Override
public long getItemId(int position) {
return position;
}
public HashMap<String,Boolean> getHashMap() {
HashMap<String, Boolean> hm = new HashMap<String,Boolean>();
hm.put("sun", boolArray.get(0));
hm.put("mon", boolArray.get(1));
hm.put("tues", boolArray.get(2));
hm.put("wed", boolArray.get(3));
hm.put("thurs", boolArray.get(4));
hm.put("fri", boolArray.get(5));
hm.put("sat", boolArray.get(6));
return hm;
}
}
Any help would be greatly appreciated, I can post more of my code if need be.

initiate gridview and checkbox in the adapter class (using find view by id).
then pass
if (checkBox.isChecked) {
gridview.setBackgroundColor(Color.rgb(x,y,z)))}

Related

use Custome ListView with TextView And CheckBox With Single Selection of CheckBox

Hear i use Custom ListView with TextView and CheckBox.
But i want that Single Selection in CheckBox At a time
One CheckBox Selected then other one is Deselect
using BaseAdapter
but This code not Work Properly ..
Please Give me Suggestion ..thnks
#Override
public View getView(final int position, View view, ViewGroup parent) {
Integer selected_position = -1;
holder = new ViewHolder();
final Items itm = rowItem.get(position);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = layoutInflater.inflate(R.layout.activity_custom_list,
parent, false);
holder.tvItemName = (TextView) view.findViewById(R.id.textView1);
holder.check = (CheckBox) view.findViewById(R.id.checkBox1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.tvItemName.setText(itm.getItems());
if (position == selected_position)
holder.check.setChecked(true);
else
holder.check.setChecked(false);
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (holder.check.isChecked()) {
selected_position = position;
} else {
selected_position = -1;
}
notifyDataSetChanged();
}
});
return view;
}}
use Custom List-View with Text-View And Check-Box With Single Selection of Check Box
So many try then finally i got the Solution I hope it is Useful Code to you All...
This code Help you to create custom List-view with Text-view and Check-box then you select one check-box and if you select another one the first should automatically be Deselected.....Thank You...
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"
tools:context="com.example.listviewdemo2.MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
activity_custom_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.listviewdemo2.CustomListActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray" >
<TextView
android:id="#+id/textView1"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="4dp"
android:layout_weight="0.39"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="4dp"/>
</LinearLayout> </LinearLayout>
String.xml
<string-array name="name">
<item>Laptop</item>
<item>Mobile</item>
<item>Desktop</item>
<item>TV</item>
<item>Pendrive</item>
<item>Router</item>
<item>Notebook</item>
<item>Tablet</item>
<item>I-pad</item>
<item>Bluetooth</item>
<item>HomeTheator</item>
</string-array>
MainActivity.java
String[] ItemName;
List<Items> rowItem;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItem = new ArrayList<Items>();
ItemName = getResources().getStringArray(R.array.name);
for(int i = 0 ; i < ItemName.length ; i++)
{
Items itm = new Items(ItemName[i]);
rowItem.add(itm);
}
list = (ListView) findViewById(R.id.listView1);
CustomListActivity adapter = new CustomListActivity(this, rowItem);
list.setAdapter(adapter);
}
Items.java
public class Items {
private String items;
private boolean selected;
public Items(String items) {
this.items = items;
}
public String getItems() {
return items;
}
public void setItemName(String name) {
this.items = name;
}
public boolean getSelected() {
return selected;
}
public boolean setSelected(Boolean selected) {
return this.selected = selected;
}}
CustomListActivity.java
public class CustomListActivity extends BaseAdapter {
Context context;
List<Items> rowItem;
View listView;
boolean checkState[];
ViewHolder holder;
public CustomListActivity(Context context, List<Items> rowItem) {
this.context = context;
this.rowItem = rowItem;
checkState = new boolean[rowItem.size()];
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
public class ViewHolder {
TextView tvItemName;
CheckBox check;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
holder = new ViewHolder();
final Items itm = rowItem.get(position);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (view == null) {
listView = new View(context);
listView = layoutInflater.inflate(R.layout.activity_custom_list,
parent, false);
holder.tvItemName = (TextView) listView
.findViewById(R.id.textView1);
holder.check = (CheckBox) listView.findViewById(R.id.checkBox1);
listView.setTag(holder);
} else {
listView = (View) view;
holder = (ViewHolder) listView.getTag();
}
holder.tvItemName.setText(itm.getItems());
holder.check.setChecked(checkState[position]);
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for(int i=0;i<checkState.length;i++)
{
if(i==position)
{
checkState[i]=true;
}
else
{
checkState[i]=false;
}
}
notifyDataSetChanged();
}
});
return listView;
}}
Show The Output :-
If you want a custom ListView with single choice CheckBox you can use something like this:
https://stackoverflow.com/a/12003125/5778152

Nothing showing on screen with custom listview adapter

As the title states, I'm having some troubles getting my custom listview adapter to work properly. The app displays nothing on the list, and gives just a blank white screen. I tested my data with a simple list I already have setup, and that worked just fine.
History.java
public class History {
public String score;
public String gametype;
public int icon;
public History() {
super();
}
public History(String score, String gametype, int icon) {
super();
this.score = score;
this.gametype = gametype;
this.icon = icon;
}
}
HistoryAdapter.java
public class HistoryAdapter extends ArrayAdapter<History> {
Context context;
int layoutResId;
History data[] = null;
public HistoryAdapter(Context context, int layoutResId, History[] data) {
super(context, layoutResId, data);
this.layoutResId = layoutResId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
HistoryHolder holder = null;
if(convertView == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
convertView = inflater.inflate(layoutResId, parent, false);
holder = new HistoryHolder();
holder.imageIcon = (ImageView)convertView.findViewById(R.id.icon);
holder.textTitle = (TextView)convertView.findViewById(R.id.gameType);
holder.textScore = (TextView)convertView.findViewById(R.id.score);
convertView.setTag(holder);
}
else
{
holder = (HistoryHolder)convertView.getTag();
}
History history = data[position];
holder.textScore.setText(history.score);
holder.textTitle.setText(history.gametype);
holder.imageIcon.setImageResource(history.icon);
return convertView;
}
static class HistoryHolder
{
ImageView imageIcon;
TextView textTitle;
TextView textScore;
}
}
Implementation
for(int i = 0; i < games.length(); i++) {
JSONObject c = games.getJSONObject(i);
JSONObject gameStats = games.getJSONObject(i).getJSONObject(TAG_STATS);
type[i] = c.getString(TAG_TYPE);
champId[i] = c.getString("championId");
cs[i] = gameStats.getString("minionsKilled");
kills[i] = gameStats.getString("championsKilled");
deaths[i] = gameStats.getString("numDeaths");
assists[i] = gameStats.getString("assists");
win[i] = gameStats.getString("win");
if(win[i].equals("true"))
win[i] = "Victory";
else
win[i] = "Defeat";
if(type[i].equals("RANKED_SOLO_5x5"))
type[i] = "Ranked (Solo)";
if(type[i].equals("CAP_5x5"))
type[i] = "TeamBuilder";
if(type[i].equals("NORMAL"))
type[i] = "Unranked";
score[i] = kills[i] +"/" + deaths[i] + "/" + assists[i];
historyData[i] = new History(score[i], champId[i], R.drawable.ic_launcher); // Placeholder image
}
adapter = new HistoryAdapter(MatchHistoryActivity.this,
R.layout.list_adapter,
historyData);
list.setAdapter(adapter);
listview.xml
<?xml version="1.0" encoding="utf-8"?>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/list"
android:background="#111111">
</ListView>
list_item.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:background="#111111"
android:padding="6dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/score"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="0/0/0 KDA"
android:textSize="12sp" />
<TextView
android:id="#+id/gameType"
android:textColor="#C49246"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/score"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_marginLeft="5dp"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:textSize="16sp" />
</RelativeLayout>
I think you should replace ArrayAdapter by BaseAdapter and implement all required method e.g. getItemId(), getItem(), getCount(), getView().
It should work fine!.
Below is example code of mine, dont care about what is MusicModel.
protected class MusicCustomAdapter extends BaseAdapter {
private Activity context;
private List<MusicModel> musicModelList;
private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
public MusicCustomAdapter(Activity context, List<MusicModel> musicModelList) {
this.context = context;
this.musicModelList = musicModelList;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public Object getItem(int position) {
return this.musicModelList.get(position);
}
#Override
public int getCount() {
return this.musicModelList.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = context.getLayoutInflater().inflate(R.layout.song_item, null);
}
MusicModel musicModel = (MusicModel) getItem(position);
TextView tvMusicName = (TextView) view.findViewById(R.id.tv_song_name);
tvMusicName.setText(musicModel.getName());
TextView tvArtist = (TextView) view.findViewById(R.id.tv_artist);
tvArtist.setText(musicModel.getArtist());
TextView tvDuration = (TextView) view.findViewById(R.id.tv_duration);
tvDuration.setText(sdf.format(musicModel.getDuration()));
ImageView imgThumbnail = (ImageView) view.findViewById(R.id.img_thumbnail);
imgThumbnail.setImageDrawable(musicModel.getThumbnail());
return view;
}
}
Hope this help.
You need to override getCount() in your custom adapter.
It will return the number of entries in your ListView.
#Override
public int getCount() {
return myArrayList.size();
}

Android Gridview - Not able to select image inside Griditem with Android-Box remote

I am creating a android app in which i have list of channels(items) in a Custom GridView.
I have a favorite icon associated with each channel to add them in favorites list.
On click of this favorite icon the channel gets added to the Favorites List of channels.
When i use a android box remote i am not able to select the ImageView for favorite.
Instead the whole GridItem gets selected.
The single grid item is a LinearLayout which mainly has two ImageViews in it.
View code for a single grid-item of the gridview
<?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="fill_parent"
android:focusable="false"
android:clickable="true"
android:orientation="vertical" >
<ImageView
android:id="#+id/channelLogo"
android:layout_width="75dip"
android:layout_height="75dip"
android:layout_gravity="center"
android:focusable="false"
android:contentDescription="#string/app_name"/>
<TextView
android:id="#+id/channelName"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<TextView
android:id="#+id/channelStatus"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<ImageView
android:id="#+id/addToFavourite"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="false"
android:contentDescription="Add to favourites"
android:src="#drawable/addfavorites"
/>
</LinearLayout>
Code for my grid adapter where i handle the click of the ImageView (for adding a channel to favorite).
public class GridAdapter extends BaseAdapter {
private Context mContext;
private int resourceId;
private ArrayList<Item> itemList = new ArrayList<Item>();
private ArrayList<Category> categoryList = new ArrayList<Category>();
private int size;
private Integer[] mThumbIds;
private ViewGroup gridGroup;
private static final String PREFS_FAVOURITES = "favourites";
public GridAdapter(MainActivity c, int layoutResourceId, ArrayList<Item> data, int gsize) {
mContext = c;
resourceId = layoutResourceId;
itemList = data;
size = gsize;
mThumbIds = new Integer[gsize];
for(int i=0;i<mThumbIds.length;i++) {
mThumbIds[i] = R.drawable.ic_launcher;
}
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int arg0) {
return mThumbIds[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
class ViewHolder {
ImageView imageUrl;
TextView channelNameTxt;
TextView channelStatusTxt;
ImageView imgFavourite;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String contextClass = mContext.getClass().toString();
ViewHolder holder;
gridGroup = parent;
View grid = null;
if(convertView==null){
grid = new View(mContext);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
if (contextClass.contains("MainActivity") || contextClass.contains("FavoriteActivity")) {
grid = inflater.inflate(R.layout.grid_item, parent, false);
}
}else{
grid = (View)convertView;
return grid;
}
if (contextClass.contains("MainActivity")) {
if (position < itemList.size()) {
holder = new ViewHolder();
holder.channelNameTxt = (TextView) grid
.findViewById(R.id.channelName);
String channelName = itemList.get(position).getChannelName().replace("\n", "").replace("\r", "");
holder.channelNameTxt.setText(channelName);
holder.channelStatusTxt = (TextView) grid
.findViewById(R.id.channelStatus);
holder.channelStatusTxt
.setText(itemList.get(position).getStatus());
if(itemList.get(position).getStatus().equalsIgnoreCase("Online")) {
holder.channelStatusTxt.setTextColor(Color.GREEN);
} else if(itemList.get(position).getStatus().equalsIgnoreCase("Offline")) {
holder.channelStatusTxt.setTextColor(Color.RED);
}
holder.imageUrl = null;
try {
holder.imageUrl = (ImageView) grid
.findViewById(R.id.channelLogo);
holder.imageUrl.setTag(itemList.get(position).getImageUrl());
new DownloadImagesTask().execute(holder.imageUrl);
notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex.toString());
}
final Item info = itemList.get(position);
holder.imgFavourite = (ImageView)grid.findViewById(R.id.addToFavourite);
holder.imgFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//GridView gridview1;
if(mContext.getClass().toString().contains("MainActivity")) {
GridView gv = (GridView)gridGroup;
final int position = gv.getPositionForView((View) v.getParent());
Toast.makeText(mContext, "Position is :" + position, Toast.LENGTH_SHORT).show();
SharedPreferences settings = mContext.getSharedPreferences(PREFS_FAVOURITES, 0);
String favourites = settings.getString("favourites", "");
Item clicked_item = itemList.get(position);
String sep1 = "<sep1>";
String sep = "<sep>";
String favourite = clicked_item.getChannelUrl()+sep1+clicked_item.getChannelName()+sep1+clicked_item.getStatus()+sep1+"Favorite"+sep1+clicked_item.getImageUrl()+sep;
favourite = favourite.replace("\n", "").replace("\r", "");
if(!favourites.contains(favourite))
favourites = favourites+favourite;
SharedPreferences.Editor editor = settings.edit();
editor.putString("favourites", favourites);
editor.commit();
}
}
});
grid.setTag(holder);
}
}
return grid;
}
This works fine on a android phone.

My listView shows only one record of 3

I have a list view which displays only one record always, I've traced my program and find that there are 3 records in my arrayList which I'm passing to the listView adapter. After tracing into getView of list view I find that It executes more that 3 times with position of 0!
I have no idea what's the problem, please help me if you can.
activity_news.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:background="#color/background"
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=".News" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#+id/lvNews"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp" />
</ScrollView>
</RelativeLayout>
this is row template for listView: news_row.xml
<?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="wrap_content"
android:background="#drawable/message_row_style"
android:layout_gravity="right"
android:gravity="right"
android:orientation="vertical" >
<LinearLayout
android:layout_marginTop="50dp"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/txtTitle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textColor="#color/dark_purple"
android:layout_gravity="right"
android:gravity="right"
android:background="#color/red"
/>
<TextView
android:id="#+id/txtDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#color/dark_purple"
android:layout_gravity="right"
android:background="#color/blue"
android:gravity="right" />
</LinearLayout>
</LinearLayout>
newsAdapter.java:
public class NewsAdapter extends BaseAdapter{
private Context context;
private ArrayList<News> list;
private Activity activity;
public NewsAdapter(Context c,Activity activity,ArrayList<News> l) {
Log.d("Ehsan", "News Adapter Constructor");
context = c;
list = l;
this.activity = activity;
}
#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 position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
News temp = list.get(position);
title.setText(temp.getTitle());
date.setText(temp.getsDate());
title.setTag(temp.getid());
title.setOnClickListener(onClickListener);
return row;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String date = null,title = null,description = null;
int id=1;
Intent i = null;
News news = new News(activity);
news.load(id);
date = news.getsDate()+" - ";
title = news.getTitle();
description = news.getDescription();
i = new Intent(activity,ShowInfo.class);
i.putExtra("date", date);
i.putExtra("title", title);
i.putExtra("description", description);
activity.startActivity(i);
activity.finish();
}
};
}
Do following changes in your getView
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
ViewHolder holder=new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
convertView.setTag(holder);
}
ViewHolder hold=(ViewHolder)convertView.getTag();
News temp = list.get(position);
hold.title.setText(temp.getTitle());
hold.date.setText(temp.getsDate());
title.setOnClickListener(onClickListener);
return row;
}
add this class in your adapter file
static class ViewHolder
{
TextView title;
TextView date;
}
You should call super in the constructor of your adapter change your adapter as following:
public class NewsAdapter extends ArrayAdapter<News>{
private Context context;
private ArrayList<News> list;
private Activity activity;
public NewsAdapter(Context c,Activity activity,ArrayList<News> l) {
super(c,-1,l);//<-- **pass your item list to super**
Log.d("Ehsan", "News Adapter Constructor");
context = c;
list = l;
this.activity = activity;
}
#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 position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.news_row, parent,false);
TextView title = (TextView) row.findViewById(R.id.txtTitle);
TextView date = (TextView) row.findViewById(R.id.txtDate);
News temp = list.get(position);
title.setText(temp.getTitle());
date.setText(temp.getsDate());
title.setTag(temp.getid());
title.setOnClickListener(onClickListener);
return row;
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
String date = null,title = null,description = null;
int id=1;
Intent i = null;
News news = new News(activity);
news.load(id);
date = news.getsDate()+" - ";
title = news.getTitle();
description = news.getDescription();
i = new Intent(activity,ShowInfo.class);
i.putExtra("date", date);
i.putExtra("title", title);
i.putExtra("description", description);
activity.startActivity(i);
activity.finish();
}
};
}

Custom List View with OnClickListener

I have custom ListView layout with a TextView and CheckBox. Everything works fine.
What I want is, when I click on the CheckBox or TextView (on the single View from ListView) both should behave like one object. (I can click on the CheckBox and it does not effect the TextView and TextView has no effect on CheckBox.) Code has no problem.
I have implemented all possible solutions but problem is still there. (One single click on every object of list should consider ONE COMPLETE CLICK for complete row.) I hope I explained very well.
MAIN ACTIVITY
package com.example.smsplanner;
public class SMSPlanner extends ListActivity {
ListView contactsListView;
private String TAG = "SMSPlanner"; CheckBox check;
int count;
List<ContactInfo> list = new ArrayList<ContactInfo>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ph = new String[3];
phType = new String[3];
LoadContactListFromPhone();
ContactsAdapter contactadAdapter = new ContactsAdapter(this, list);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setListAdapter(contactadAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id)
{
TextView tx =(TextView)v.findViewById(R.id.firstname);
TextView ph =(TextView)v.findViewById(R.id.phone);
Toast.makeText(this, tx.getText().toString() + " " + ph.getText().toString() + " " + Integer.toString(count), Toast.LENGTH_SHORT).show();
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
void LoadContactListFromPhone()
{
loadlistandreturns();
}
void call()
{
Toast toast = Toast.makeText(this, "Called...",Toast.LENGTH_LONG);
toast.show();
}
}
CUSTOM ADAPTER
public class ContactsAdapter extends ArrayAdapter<ContactInfo>
{
private final Activity context;
int resourceid;
List<ContactInfo> list = null;
public ContactsAdapter(Activity context, List<ContactInfo> list) {
super(context, R.layout.contactrow, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
}
LAYOUT
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<RadioGroup
android:id="#+id/rgStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="15"
android:orientation="vertical" >
<TextView
android:id="#+id/firstname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
<RadioGroup
android:id="#+id/rgStyle2"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="85"
android:orientation="vertical" >
<CheckBox
android:id="#+id/check"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:checked="false"
android:focusable="false"
android:focusableInTouchMode="false" >
</CheckBox>
</RadioGroup>
</LinearLayout>
1. Bydefault all the Rows of the ListView are enabled to listen to click....
You must implement onItemClickListener() for the ListView....
See this example:
http://www.mkyong.com/android/android-listview-example/
you can use a CheckedTextView, or you can create a Checkable Layout, like this one :
http://tokudu.com/2010/android-checkable-linear-layout/
i think you should make adapter as
public class ContactsAdapter extends BaseAdapter {
ArrayList<ContactInfo> mlist;
Context mcontext;
public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) {
mlist = mchtlist;
mcontext = context;
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public Object getItem(int postion) {
return mlist.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// to open the selected file in resp
// do your work here
}});
chkselected .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(context,// "checked is clicke="+pos, 12).show();
if (chkselected.isChecked())
{
// do your work here
} else {
// do your work here
}
}
});
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
}

Categories

Resources