Android: ListView not working properly after scroll - android

Hi I'm trying to show text, image alternatively in list view. To load the content into my list view i had three scenarios.
1. Some times i'm getting only the text from json. So, in this case i have to hide the ImageView
2. Some cases i'm getting only the image url from json. So, in this case i have to hide the TextView
3. In other case i'm getting both image url and text from json, so, in this case i don't have to hide anything
By following these scenarios i'm loading all the content correctly at first time but when i'm scrolling top to bottom and bottom to up. All the image views are filled with images (But there is no image url for that particular position)
My adapter code is
package com.app.listviewitemid.adapter;
import java.util.ArrayList;
import com.app.listviewitemid.R;
import com.app.listviewitemid.model.Items;
import com.bumptech.glide.Glide;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ItemsAdapter extends ArrayAdapter<Items>{
ArrayList<Items> itemsArrayList;
int Resource;
LayoutInflater inflater;
Context context;
ViewHolder holder;
Button btnCheck;
Items globPosition;
public ItemsAdapter(Context context, int resource, ArrayList<Items> objects){
super(context, resource, objects);
this.context = context;
this.Resource = resource;
this.itemsArrayList = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
v = inflater.inflate(Resource, null);
holder = new ViewHolder();
holder.tvPostID = (TextView) v.findViewById(R.id.tv_post_id);
holder.tvPostText = (TextView) v.findViewById(R.id.tv_post_text);
holder.ivPostImage = (ImageView) v.findViewById(R.id.iv_post_img);
btnCheck = (Button) v.findViewById(R.id.btn_check);
v.setTag(holder);
}else{
holder = (ViewHolder) v.getTag();
}
globPosition = itemsArrayList.get(position);
holder.tvPostID.setText(itemsArrayList.get(position).getPostID());
if(globPosition.getPostText().equals(null) || globPosition.getPostText().equals("")){
}else {
holder.tvPostText.setText(globPosition.getPostText());
}
if(globPosition.getPostImage().equals(null) || globPosition.getPostImage().equals("")){
}else {
Glide.with(context).load(globPosition.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(holder.ivPostImage);
}
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("PostID", globPosition.getPostID());
}
});
return v;
}
static class ViewHolder{
TextView tvPostID;
TextView tvPostText;
ImageView ivPostImage;
}
}
adapter 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="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_post_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/post_id"
android:textColor="#000000"
android:textSize="12sp" />
<TextView
android:id="#+id/tv_post_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="12sp" />
<ImageView
android:id="#+id/iv_post_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/empty" />
<Button
android:id="#+id/btn_check"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#000000"
android:text="#string/check"
android:textColor="#FFFFFF" />
</LinearLayout>
How to get rid of this?

if(globPosition.getPostText().equals(null) || globPosition.getPostText().equals("")){
holder.tvPostText.setVisibility(View.GONE);
}else {
holder.ivPostImage.setVisibility(View.GONE);
holder.tvPostText.setVisibility(View.VISIBLE);
holder.tvPostText.setText(globPosition.getPostText());
}
if(globPosition.getPostImage().equals(null) || globPosition.getPostImage().equals("")){
holder.ivPostImage.setVisibility(View.GONE);
}else {
holder.ivPostImage.setVisibility(View.GONE);
holder.tvPostText.setVisibility(View.VISIBLE);
Glide.with(context).load(globPosition.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(holder.ivPostImage);
}

I got the idea from ankit aggarwal answer (his code is not working properly but he gave me the basic idea). And one more thing, previously i didn't get the correct position, so i changed the adapter code little bit
Code
package com.app.listviewitemid.adapter;
import java.util.List;
import com.app.listviewitemid.R;
import com.app.listviewitemid.model.Items;
import com.bumptech.glide.Glide;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ItemsAdapter extends BaseAdapter{
List<Items> itemsArrayList;
int Resource;
LayoutInflater inflater;
Context context;
Button btnCheck;
public ItemsAdapter(Context context, List<Items> items) {
this.context = context;
this.itemsArrayList = items;
}
#Override
public int getCount() {
return itemsArrayList.size();
}
#Override
public Object getItem(int location) {
return itemsArrayList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams") #Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.adapter_layout, null);
TextView tvPostID = (TextView) convertView.findViewById(R.id.tv_post_id);
TextView tvPostText = (TextView) convertView.findViewById(R.id.tv_post_text);
ImageView ivPostImage = (ImageView) convertView.findViewById(R.id.iv_post_img);
btnCheck = (Button) convertView.findViewById(R.id.btn_check);
final Items items = itemsArrayList.get(position);
tvPostID.setText(items.getPostID());
if(items.getPostText().equals(null) || items.getPostText().equals("")){
tvPostText.setVisibility(View.GONE);
}else {
//ivPostImage.setVisibility(View.GONE);
if(items.getPostImage().equals(null) || items.getPostImage().equals("")){
ivPostImage.setVisibility(View.GONE);
}else {
ivPostImage.setVisibility(View.VISIBLE);
tvPostText.setVisibility(View.GONE);
Glide.with(context).load(items.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(ivPostImage);
}
tvPostText.setVisibility(View.VISIBLE);
tvPostText.setText(items.getPostText());
}
if(items.getPostImage().equals(null) || items.getPostImage().equals("")){
ivPostImage.setVisibility(View.GONE);
}else {
ivPostImage.setVisibility(View.VISIBLE);
//tvPostText.setVisibility(View.GONE);
if(items.getPostText().equals(null) || items.getPostText().equals("")){
tvPostText.setVisibility(View.GONE);
}else {
tvPostText.setVisibility(View.VISIBLE);
tvPostText.setText(items.getPostText());
}
Glide.with(context).load(items.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(ivPostImage);
}
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("PostID", items.getPostID());
}
});
return convertView;
}
}
Thanks to ankit aggarwal

Related

Android runtime eror: the app suddenly stops

My app is to perform ListView. When it was running, the error message notified that "Unfortunately, App has stopped". Here is my code.
package com.example.admin.customadapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayList<Nation>nationifo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.ListViewNation);
nationifo = new ArrayList<>();
nationifo.add(new Nation("VietNam",1945));
nationifo.add(new Nation("Malaysia",1975));
nationifo.add(new Nation("Laos",1943));
NationAdapter adp = new NationAdapter(
MainActivity.this,
R.layout.nation_list,
nationifo
);
listView.setAdapter(adp);
}
}
Nation.java
package com.example.admin.customadapter;
public class Nation {
public String name;
public Integer year;
public Nation(String Name, Integer Year){
Name = name;
Year = year;
}
}
NationAdapter.java
package com.example.admin.customadapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class NationAdapter extends BaseAdapter {
Context mycontext;
int mylayout;
List<Nation>arrayNation;
public NationAdapter (Context context, int layout, List<Nation>nationList){
mycontext = context;
mylayout = layout;
arrayNation = nationList;
}
public int getCount() {
return arrayNation.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mycontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(mylayout,null);
TextView txtv1 = (TextView) convertView.findViewById(R.id.textView);
txtv1.setText(arrayNation.get(position).name);
TextView txtv2 =(TextView) convertView.findViewById(R.id.textView2);
txtv2.setText(String.valueOf(arrayNation.get(position).year));
return convertView;
}
}
nation_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background = "#ffffff">
<TextView
android:textColor="#ff0400"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="30dp"
android:id="#+id/textView" />
<TextView
android:textColor="#0022ff"
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView2" />
</LinearLayout>
My Android Studio is 2.2. But I don't think that this version is diferrent to another.
try to use the following
convertView = inflater.inflate(mylayout,parent,false);
instead of
convertView = inflater.inflate(mylayout,null);

Imageview getting automatically changed on scroll listview

I am new to android and facing one very comman problem of listview i googled alot but did'nt found anything usefull for my case.Hope you people show me the right direction.Whenever I am changing my image from "plus" to "tick" on click my last item image also got automatically changed on scroll.
My list_comapare_product XMl :-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white_color"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/white_color"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/img_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/crane" />
<com.mss.skyjack.custom.views.SkyjackCustomTextview
android:id="#+id/tv_product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="test"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/img_plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/plus" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/black_color" />
</LinearLayout>
Here is my Adapter :-
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ComapreProductSelectionAdapter extends BaseAdapter {
Activity activity;
List<SelectorTest> listSelector;
private LayoutInflater mLayoutInflater;
public ComapreProductSelectionAdapter(Activity activity,
List<SelectorTest> listSelector) {
this.activity = activity;
this.listSelector = listSelector;
mLayoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listSelector.size();
}
#Override
public SelectorTest getItem(int position) {
return listSelector.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int i = position;
final SelectorTest listItem = listSelector.get(position);
if (convertView == null) {
convertView = mLayoutInflater.inflate(
R.layout.list_comapare_product, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvProductName = (TextView) convertView
.findViewById(R.id.tv_product_name);
viewHolder.imgProduct = (ImageView) convertView
.findViewById(R.id.img_product);
viewHolder.imgadd = (ImageView) convertView
.findViewById(R.id.img_plus);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imgadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.imgadd.getDrawable().getConstantState() == activity
.getResources().getDrawable(R.drawable.plus)
.getConstantState()) {
viewHolder.imgadd.setImageResource(R.drawable.tick);
} else {
viewHolder.imgadd.setImageResource(R.drawable.plus);
}
}
});
return convertView;
}
static class ViewHolder {
TextView tvProductName;
ImageView imgProduct, imgadd;
View viewRightLine;
}
}
Thanks.
You need to keep track of which items have been "ticked". I copied your adapter and made necessary changes. You can just copy-paste the code and it should work.
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ComapreProductSelectionAdapter extends BaseAdapter {
Activity activity;
List<SelectorTest> listSelector;
private LayoutInflater mLayoutInflater;
private ArrayList<Integer> tickedItems = new ArrayList<Integer>();
public ComapreProductSelectionAdapter(Activity activity,
List<SelectorTest> listSelector) {
this.activity = activity;
this.listSelector = listSelector;
mLayoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listSelector.size();
}
#Override
public SelectorTest getItem(int position) {
return listSelector.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int i = position;
final SelectorTest listItem = listSelector.get(position);
if (convertView == null) {
convertView = mLayoutInflater.inflate(
R.layout.list_comapare_product, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvProductName = (TextView) convertView
.findViewById(R.id.tv_product_name);
viewHolder.imgProduct = (ImageView) convertView
.findViewById(R.id.img_product);
viewHolder.imgadd = (ImageView) convertView
.findViewById(R.id.img_plus);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imgadd.setTag(position);
viewHolder.imgadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(tickedItems.contains((Integer)v.getTag()) {
//Already ticked, set to plus
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.plus));
tickedItems.remove((Integer)v.getTag());
} else {
tickedItems.add((Integer)v.getTag());
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.tick));
}
}
});
if(tickedItems.contains(position))
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.tick));
else
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.plus));
return convertView;
}
static class ViewHolder {
TextView tvProductName;
ImageView imgProduct, imgadd;
View viewRightLine;
}
}
As an extra, don't use ImageView.setImageResource() as it is inefficient.
Quote from Android docs about ImageView.setImageReource()
This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead.

Android Single page calendarview

I am trying to develop a calendar application which displays all the months in a year in a single activity .I am having troubles with it . This is the view that i want to make . I am so lost :/
ListViewAdapter:
package com.example.calendar15;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class CalendarListAdapter extends BaseAdapter {
private Context mContext;
String[] months;
public String[] numbers;
// Constructor
public CalendarListAdapter(Context c,String[] months) {
mContext = c;
this.months=months;
}
public int getCount() {
return months.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.grid, parent, false);
}
// Lookup view for data population
TextView tvTitle = (TextView) convertView.findViewById(R.id.date);
Log.d("months[position]",""+months[position]);
tvTitle.setText(months[position]);
/**/
String[] numbers = { "1", "2", "3", "4", "5", "6", "7","8","9","10","11","12"};
/*TextView tvDate1 = (TextView) convertView.findViewById(R.id.text1);
Log.d("numbers[position]",""+numbers[position]);
tvDate1.setText(numbers[position]);*/
GridView gridview = (GridView)convertView.findViewById(R.id.gridview);
CalendarGridAdapter calendarGridAdapter = new CalendarGridAdapter(mContext, numbers);
gridview.setAdapter(calendarGridAdapter);
return convertView;
}
}
GridViewAdapter:
package com.example.calendar15;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class CalendarGridAdapter extends BaseAdapter {
Context mContext;
String[] number;
CalendarGridAdapter(Context context, String[] numbers) {
this.mContext = context;
this.number = numbers;
Log.d("number.length",""+number.length);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return number.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return number[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.calendar_item, parent, false);
}
// Lookup view for data population
TextView tvTitle = (TextView) convertView.findViewById(R.id.date);
Log.d("number[position]",""+number[position]);
tvTitle.setText(number[position]);
return convertView;
}
}
Grid.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#727272"
android:textSize="16sp"
android:gravity="center"
android:text="date"
android:textStyle="normal" />
<GridView
android:id="#+id/gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:listSelector="#android:color/transparent"
android:numColumns="7"
android:stretchMode="columnWidth" />
</GridLayout>
calendar_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Datelayer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:gravity="center"
android:orientation="vertical"
android:padding="2dip" >
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="date"
android:textColor="#727272"
android:textSize="16sp"
android:textStyle="normal" >
</TextView>
</LinearLayout>
Solution
I changed the height of Gridview from wrap_content and set it about 200dp - the height of elements to be inflated multiplied by total no of rows. (you could set it dynamically or in the xml as per your requirements ). I hope this helps others as well

Custom ListView not showing any items

I am trying to display a custom listview but nothing appears.
My activity:
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import com.example.elnoorgeh.ServerAPI;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class BlogFragment extends Fragment {
JSONArray jArray;
TextView title;
RelativeLayout layout;
int previousID = 0;
int currentID = 0;
ArrayList<String> titles;
ArrayList<String> contents;
ListView list;
public BlogFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_blog, container,
false);
new AsyncFetch().execute();
return rootView;
}
private class AsyncFetch extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
jArray = new JSONArray();
jArray = ServerAPI.getData();
titles = new ArrayList<String>();
contents = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
String blogTitle = null;
String content = null;
try {
blogTitle = jArray.getJSONObject(i).getString("title");
content = jArray.getJSONObject(i).getString("content");
titles.add(blogTitle);
contents.add(content);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println(blogTitle);
System.out.println(content);
}
// display(titles, contents);
return null;
}
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeAllViews();
CustomList adapter = new CustomList(getActivity(), titles);
list = new ListView(getActivity());
System.out.println("list done");
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}
}
public void display(ArrayList<String> t, ArrayList<String> c) {
}
}
Custom ListView class:
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomList extends ArrayAdapter<String> {
private final Activity context;
private final ArrayList<String> web;
// private final Integer[] imageId;
public CustomList(Activity context, ArrayList<String>web) {
super(context, R.layout.fragment_listview);
this.context = context;
this.web = web;
// this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.fragment_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText((CharSequence) web.get(position));
// imageView.setImageResource(imageId[position]);
return rowView;
}
}
fragment_blog:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/blogPage"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
<TextView
android:id="#+id/txtLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="20"
android:singleLine="false"
android:textSize="16dp" />
</RelativeLayout>
fragment_listview:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<ImageView
android:id="#+id/img"
android:layout_width="50dp"
android:layout_height="50dp" />
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="50dp" />
</TableRow>
</TableLayout>
I can't find any errors or notice something irregular, so why is that happening?
you should extend BaseAdapter and implement abstract methods
#Override
public int getCount() {
return web.size();
}
#Override
public Object getItem(int position) {
return web.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
also you might change
txtTitle.setText((CharSequence) web.get(position));
to
txtTitle.setText((CharSequence) getItem(position));
now your adapter don't know size of web array
edit:
you can get one inflater in constructor and keep in class, no need to getting inflater each time (little bit better for perfomance)
LayoutInflater inflater = context.getLayoutInflater();
edit 2:
localhost put proper comment - you are removing all Views from RelativeLayout, also ListView, and creating new ListView without adding to Relative. keeping reference will not auto-add View
protected void onPostExecute(Object result) {
layout = (RelativeLayout) getView().findViewById(R.id.blogPage);
layout.removeView(getView().findViewById(R.id.txtLabel);
//assuming you need to remove only txtLabel
CustomList adapter = new CustomList(getActivity(), titles);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getActivity(),
"You Clicked at " + titles.get(position),
Toast.LENGTH_SHORT).show();
}
});
}

set a listener for widgets in items of a listview

I meet a problem developing an android project.
Using adapter, I place many items in a ListView, and there is an ImageButton in each item. Now I want to set a click listener for these ImageButtons. What should I do?
This achieves your desired result. Its functionality is the button itself has a click response different from the container, which also has a response.
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView lv = (ListView) findViewById( R.id.list );
lv.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
Toast.makeText( MainActivity.this,
"List item clicked",
Toast.LENGTH_SHORT).show();
}
});
ArrayList<String> items = new ArrayList<String>();
items.add( "item1");
items.add( "item2");
items.add( "item3");
ListAdapter adapter = new ListAdapter( this, items);
lv.setAdapter( adapter );
}
}
ListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.BaseAdapter;
import android.widget.Toast;
import java.util.List;
public class ListAdapter extends BaseAdapter {
public ListAdapter(Context context,
List<String> items ) {
inflater = LayoutInflater.from( context );
this.context = context;
this.items = items;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
String item = items.get(position);
View v = null;
if( convertView != null )
v = convertView;
else
v = inflater.inflate( R.layout.item, parent, false);
TextView itemTV = (TextView)v.findViewById( R.id.item);
itemTV.setText( item );
ImageButton button =
(ImageButton)v.findViewById( R.id.button);
button.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
Toast.makeText( context,
"ImageButton clicked",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
private Context context;
private List<String> items;
private LayoutInflater inflater;
}
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="wrap_content"
android:descendantFocusability="blocksDescendants" >
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="28sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:src="#drawable/emo_im_cool" />
</RelativeLayout>
list.xml
<?xml version="1.0" encoding="utf-8" ?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/list" />
Try it out and hopefully you can see what's going on to learn what you need

Categories

Resources