I'm trying to implement button on each row in ListView, but I saw many topics and I don't succeeded to add code to mine. Here is my MainActivity :
public class MainActivity extends AppCompatActivity {
private ArrayAdapter<String> itemsAdapter;
private ArrayList<String> items;
private ImageButton formButton;
private ListView lvMain;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
commonFunction();
}
public void commonFunction() {
lvMain = (ListView) findViewById(R.id.lvMain);
items = new ArrayList<String>();
readItems();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items);
lvMain.setAdapter(itemsAdapter);
formButton = (ImageButton) findViewById(R.id.btnPlus);
formButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setLayoutActivity();
}
});
}
}
Here is my activity_main.xml :
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/lvMain"
android:layout_above="#+id/btnPlus" />
<ImageButton
android:layout_width="match_parent"
android:layout_height="65dp"
android:id="#+id/btnPlus"
android:layout_alignParentBottom="true"
app:srcCompat="#mipmap/ic_plus_foreground" />
Does someone any idea how to do ?
Create custom adapter with custom row layout file and add button on that row file and bind it to List/Recycler view. So it will inflate in all row.
Add below code in row_list.xml file.
<ImageButton
android:layout_width="match_parent"
android:layout_height="65dp"
android:id="#+id/btnPlus"
android:layout_alignParentBottom="true"
app:srcCompat="#mipmap/ic_plus_foreground" />
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
private ArrayList data;
private static LayoutInflater inflater = null;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(ArrayList d) {
/********** Take passed values **********/
data = d;
/*********** Layout inflater to call external xml layout () ***********/
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public ImageButton button;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.row_list, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.button = (ImageView) vi.findViewById(R.id.btnPlus);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Button click
}
});
return vi;
}}
Hope it will solve problem.
Happy coding!!
Crate custom adapter and bind it with the ListView.
Inflate custom layout for each row in the adapter.
You can put your button in the custom layout file.
public class CustomAdapter extends ArrayAdapter<String> {
private Context context;
private int singleRowLayoutId;
public CustomAdapter(Context context, int singleRowLayoutId, String []titles, String []desc, int []images ) {
super(context, singleRowLayoutId,titles);
this.context=context;
this.singleRowLayoutId=singleRowLayoutId; //custom row layout for list view item
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row=convertView;
CustomViewHolder holder=null;
if(row==null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//view object of single row of list view
row = inflater.inflate(singleRowLayoutId, parent, false);
//by using holder, we make sure that findViewById() is not called every time.
holder=new CustomViewHolder(row);
row.setTag(holder);
}
else
{
holder=(CustomViewHolder)row.getTag();
}
return row;
}
private class CustomViewHolder {
private ImageButton mbtn;
CustomViewHolder(View view)
{
mbtn=(ImageButton)view.findViewById(R.id.btn);
mbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle button click here
}
});
}
}
I think that this is what you need - create a separate layout for the rows in the list view. Then create a custom adapter, where you are adding this layout as row layout and then set this adapter to your list view. Here are the details with examples:
Android custom Row Item for ListView
Related
Am building an app for exploring files and am using the android native resource layout for data population called android.R.simple_list_item_1, i have tried going through the methods of a listview to see if i can add a drawable to the left of each item in my list but didn't manage. So the only way i get to access a view from a listview is on event OnItemClick where the view tapped is passed as parameter to the method and then i can format it this way for the drawable
public class MainActivity extends AppCompatActivity {
//Define a listview for holding the data mined from storage
public ListView mydata;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Define the listview
mydata=findViewById(R.id.data);
mydata.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
//Cast view to TextView at position
TextView r=(TextView)view;
//get the drawable and set to textview
Drawable mydraw= ResourcesCompat.getDrawable(getResources(),R.drawable.ic_baseline_file_copy_24,null);
r.setCompoundDrawables(mydraw,null,null,null);
}
}
}
Is there in which i can get all the views in the listview, create a loop, iterate through all of them and cast to TextView array and then set my drawable to the TextView(s)?
final static class YourItemClass {
...
}
final static class ViewHolder {
TextView mTextView;
private ViewHolder(#NonNull final View simpleListItem1) {
if (!(simpleListItem1 instanceof TextView)) throw new IllegalArgumentException("TextView was expected as root of Layout");
this.mTextView = (TextView)simpleListItem1;
}
}
final class CustomArrayAdapter extends ArrayAdapter<YourItemClass> {
private final Drawable mDrawable;
private final LayoutInflater mLayoutInflater;
public CustomArrayAdapter(#NonNull final Context context, #NonNull final List<YourItemClass> objects) {
super(context, resource, objects);
this.mDrawable = ResourcesCompat.getDrawable(getResources(),R.drawable.ic_baseline_file_copy_24,null);
this.mLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull final ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = this.mLayoutInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
final YourItemClass cYourItemClassAtSpecificPosition = this.getItem(position);
holder.mTextView.setCompoundDrawables(this.mDrawable, null, null, null);
return convertView;
}
}
Then from your Activity/Fragment:
private void setItemsToListView(#NonNull final List<YourItemClass> items) {
mListView.setAdapter(new CustomArrayAdapter(getActivity(), items));
}
This code will run "setCompoundDrawables()" for each row displayed in the ListView.
I want create a horizontal recycle view and i writed this code:
in main activity xml
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" >
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
And this is adapter class
public class AdapterNote extends ArrayAdapter<StructCategory> {
public AdapterNote(ArrayList<StructCategory> array) {
super(G.context, R.layout.adapter_category, array);
}
private static class ViewHolder {
public TextView txtTitle;
public ViewHolder(View view) {
txtTitle = (TextView) view.findViewById(R.id.cat_txt);
}
public void fill(final ArrayAdapter<StructCategory> adapter, final StructCategory item, final int position) {
txtTitle.setText(item.title);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
StructCategory item = getItem(position);
if (convertView == null) {
convertView = G.inflater.inflate(R.layout.adapter_category, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.fill(this, item, position);
return convertView;
}}
In the MainClass setadapter
setadapter function has error :
The type android.support.v4.view.NestedScrollingChild2 cannot be resolved. It is indirectly referenced from required .class files
I imported support v4 api 20 and v7compat v20 and v7 recycleview api 20
but dont work my code
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);
adapter = new AdapterNote(G.tasksCategory);
myList.setAdapter(adapter);
and i create xml for adapter class:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" android:padding="8dip" android:gravity="right">
<TextView
android:id="#+id/cat_txt"
android:layout_width="80dp"
android:layout_height="80dp"
android:background="#drawable/category_txt"
android:gravity="center_vertical|center"
android:text="TextView"
android:textColor="#000" />
</LinearLayout>
please help me for this problem
As you are using RecyclerView, extends your adapter class by RecyclerView.Adapter<>.
Please refer this : https://www.google.com/amp/s/www.androidhive.info/2016/01/android-working-with-recycler-view/amp/
I edit my code Like recycleview adapter example:
please check my code and fix it
Error txt on Classname and MyViewHolder :
The hierarchy of the type AdapterCategory is inconsistent
in the problem section show this error:
The project was not built since its build path is incomplete. Cannot find the class file for android.support.v4.view.NestedScrollingChild2. Fix the build path then try building this project
public class AdapterCategory extends RecyclerView.Adapter<AdapterCategory.MyViewHolder> {
private ArrayList<StructCategory> categoryList;
private ItemClickListener mClickListener;
AdapterCategory(Context context, ArrayList<StructCategory> categoryList) {
G.inflater = LayoutInflater.from(context);
this.categoryList = categoryList;
}
// inflates the row layout from xml when needed
#Override
#NonNull
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = G.inflater.inflate(R.layout.adapter_category, parent, false);
return new MyViewHolder(view);
}
// binds the data to the view and textview in each row
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
StructCategory hList = categoryList.get(position);
holder.myTextView.setText(hList.title);
}
// total number of rows
#Override
public int getItemCount() {
return categoryList.size();
}
// stores and recycles views as they are scrolled off screen
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView myTextView;
MyViewHolder(View itemView) {
super(itemView);
myTextView = (TextView) itemView.findViewById(R.id.cat_txt);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null)
mClickListener.onItemClick(view, getAdapterPosition());
}
}
// convenience method for getting data at click position
public StructCategory getItem(int id) {
return categoryList.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}}
I'm trying to implement an Android app for sudoku game, and i created a customized adapter for that. i want make edit text for cells the user is allowed to modify, and textview for cell filled by the program, the number of ediTexts and textViews will be random. how do specify that in the adapter ?
This is my adapter :
public class SodukuAdapter extends BaseAdapter {
ArrayList<String> items;
static Activity mActivity;
private static LayoutInflater inflater = null;
public SodukuAdapter (Activity activity, ArrayList<String> tempTitle,) {
mActivity = activity;
items = tempTitle;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public final int getCount() {
return items.size();
}
#Override
public final Object getItem(int position) {
return items.get(position);
}
#Override
public final long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = null;
v = inflater.inflate(R.layout.item, null);
EditText et = (EditText) v.findViewById(R.id.et);
et.setText(items.get(position));
return v;
}
}
You can place both views in the same parent (e. g. parent is a RelativeLayout or a FrameLayout) so they are on top of each other. Than you simply hide one of them and show the other using setVisibility() in your getView() method of the adapter.
Of course you would need a datasource object which keeps track of whether a view should show the TextView or the EditText:
class SodokuItem {
public boolean isStatic;
public String text;
}
...
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = inflater.inflate(R.layout.item, null);
SodokuItem item = items.get(position);
EditText et = (EditText) v.findViewById(R.id.et);
TextView tv = (TextView) v.findViewById(R.id.tv);
if(item.isStatic){
et.setVisibility(GONE);
tv.setText(item.text);
}else{
tv.setVisibility(GONE);
et.setText(item.text);
}
return v;
}
I've searched a lot this but I really did not find what I need exactly.
What I want is :
I have a listview and load it on my main class. I load it like this:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(Main.this,
R.layout.myrow,R.id.text );
if (friends != null) {
for (ParseObject friend : friends) {
adapter.add((String) friend.get("name"));
}
}
setListAdapter(adapter);
and myrow layout xml is here:
< RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center" >
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/my_prog"
></ProgressBar>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="25sp" >
</TextView>
</RelativeLayout >
You can see I have progress bar on textview so I need to reach it and set it's visible. I mean sometimes I set it invisible sometimes visible
What I did is:
On my MainActivity on create method the code is here :
ProgressBar my_prog;
my_prog=(ProgressBar)findViewById(R.id.my_prog);
my_prog.setVisibility(View.INVISIBLE);
The error is:
07-16 13:35:39.219: E/AndroidRuntime(29096): java.lang.RuntimeException: Unable to start activity ComponentInfo{....MainActivity}: java.lang.NullPointerException
I think I cant reach my_prog on my main activity but I need it.
How can I do that.
thanks in adnvace...
You need to implement a custom Adapter to do this. I have written this ExampleAdapter to show you how it works, I commented all the important parts:
public class ExampleAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final List<ParseObject> objects;
private final boolean[] activated;
public ExampleAdapter(Context context, List<ParseObject> objects) {
this.inflater = LayoutInflater.from(context);
this.objects = objects;
this.activated = new boolean[objects.size()];
}
public void showProgressBar(int position, boolean visible) {
this.activated[position] = visible;
notifyDataSetChanged();
}
#Override
public int getCount() {
return this.objects.size();
}
#Override
public ParseObject getItem(int position) {
return this.objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// If the convertView is null, we need to inflate a new one
if(convertView == null) {
// We inflate the view with your layout
convertView = inflater.inflate(R.layout.myrow, parent, false);
// Here we create a view holder object which keeps a
// reference to the Views in this row so we have to
// perform the expensive findViewById() only once
ViewHolder holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.my_prog = (ProgressBar) convertView.findViewById(R.id.my_prog);
// The view holder is set as tag to the view so we can access it later
convertView.setTag(holder);
}
// We retrieve the ParseObject for the current position
ParseObject parseObject = getItem(position);
// And get the view holder from the View
ViewHolder holder = (ViewHolder) convertView.getTag();
// We read the data we need from the ParseObject
String name = parseObject.get("name");
// And here is the visibility logic
int progressBarVisibility = this.activated[position] ? View.VISIBLE : View.GONE;
int textViewVisibility = this.activated[position] ? View.GONE : View.VISIBLE;
// Now we set the data to the Views through the view holder
holder.text.setText(name);
holder.text.setVisibility(textViewVisibility);
holder.my_prog.setVisibility(progressBarVisibility);
return convertView;
}
// This is our view holder class. It keeps a reference to the Views
// inside each row so we have to perform the expensive
// findViewById() only once
private class ViewHolder {
public TextView text;
public ProgressBar my_prog;
}
}
You can use the ExampleAdapter like this:
if(friends != null) {
ExampleAdapter adapter = new ExampleAdapter(Main.this, friends);
setListAdapter(adapter);
}
If you want to show a ProgressBar at a specific position you just do this:
// Shows the ProgressBar in the first row
adapter.showProgressBar(0, true)
I'm trying to make a task manager, and I only have one problem. I have a listview that gets inflated. All the elements in the listview are correct. The problem is that when I select an item, the listview will select another item away. I've heard listviews repopulate the list as it scrolls down to save memory. I think this may be some sort of problem. Here is a picture of the problem.
If i had more apps loaded, then it would continue to select multiple at once.
Here is the code of my adapter and activity and XML associated
public class TaskAdapter extends BaseAdapter{
private Context mContext;
private List<TaskInfo> mListAppInfo;
private PackageManager mPack;
public TaskAdapter(Context c, List<TaskInfo> list, PackageManager pack) {
mContext = c;
mListAppInfo = list;
mPack = pack;
}
#Override
public int getCount() {
return mListAppInfo.size();
}
#Override
public Object getItem(int position) {
return mListAppInfo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
}
});
return convertView;
public class TaskManager extends Activity implements Runnable
{
private ProgressDialog pd;
private TextView ram;
private String s;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.taskpage);
setTitleColor(Color.YELLOW);
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run()
{
//System.out.println("In Taskmanager Run() Thread");
final PackageManager pm = getPackageManager();
final ListView box = (ListView) findViewById(R.id.cBoxSpace);
final List<TaskInfo> CK = populate(box, pm);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
ram.setText(s);
box.setAdapter(new TaskAdapter(TaskManager.this, CK, pm));
//System.out.println("In Taskmanager runnable Run()");
endChecked(CK);
}
});
handler.sendEmptyMessage(0);
}
Taskinfo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal">
<ImageView
android:id="#+id/tmImage"
android:layout_width="48dp"
android:layout_height="48dp"
android:scaleType="centerCrop"
android:adjustViewBounds="false"
android:focusable="false" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tmbox"
android:lines="2"/>
</LinearLayout>
Taskpage.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="fill_parent"
android:orientation="vertical">
<ListView
android:id="#+id/cBoxSpace"
android:layout_width="wrap_content"
android:layout_height="400dp"
android:orientation="vertical"/>
<TextView
android:id="#+id/RAM"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" />
<Button
android:id="#+id/endButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="End Selected Tasks" />
</LinearLayout>
Any ideas for what reason mutliple items are selected with a single click would be GREATLY appreciated. I've been messing around with different implementations and listeners and listadapters but to no avail.
I think the point is you only save checking state in the view(v.setSelected).
And you reuse these view, so its checkbox is always not change its state.
You can create a state array to save every checking state of every TaskInfo, and check this array when you create a view.
for example
// default is false
ArrayList<Boolean> checkingStates = new ArrayList<Boolean>(mListAppInfo.size());
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
final CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(checkingStates.get(position));
convertView.setSelected(checkingStates.get(position));
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(v.isSelected())
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
checkingStates.get(position) = false;
}
else
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
checkingStates.get(position) = true;
}
}
});
return convertView;
}
I'm not 100% sure what you are trying to do, but part of your problem might be related to the condition in your onClick method:
if(v.isSelected())
I think you want that to read
if(v.isChecked())
isSelected is inherited from View, and it means something different from isChecked
Also, the whether the CheckBox is checked or not is independent from your data model since it is a recycled view. Your CheckBox should be checked based on entry (I'm assuming your TextInfo class has an isChecked() method that returns a boolean:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
TaskInfo entry = mListAppInfo.get(position);
if (convertView == null)
{
LayoutInflater inflater = LayoutInflater.from(mContext);
//System.out.println("Setting LayoutInflater in TaskAdapter " +mContext +" " +R.layout.taskinfo +" " +R.id.tmbox);
convertView = inflater.inflate(R.layout.taskinfo,null);
}
ImageView ivIcon = (ImageView)convertView.findViewById(R.id.tmImage);
ivIcon.setImageDrawable(entry.getIcon());
TextView tvName = (TextView)convertView.findViewById(R.id.tmbox);
tvName.setText(entry.getName());
CheckBox checkBox = (CheckBox)v.findViewById(R.id.tmbox);
checkBox.setChecked(entry.isChecked());
}
I don't think you need the View.OnClickListener you are attaching to convertView. You should handle that in the OnItemClickListener attached to the ListView. Assuming your ListView is called listView and TaskInfo instances have setChecked and isChecked methods:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
entry = mListAppInfo.get(position);
entry.setChecked(!entry.isChecked());
}
});
First of all don't set the list checked or unchecked on view position.
because view position means only visible items position in your listview but you would like to set checked or uncheked status on a particular list item.
That's why this problem arises in your code.
You have the need to set the items checked and unchecked on your custom arraylist getter setter like the code i have attached below:
package com.app.adapter;
public class CategoryDynamicAdapter {
public static ArrayList<CategoryBean> categoryList = new ArrayList<CategoryBean>();
Context context;
Typeface typeface;
public static String videoUrl = "" ;
Handler handler;
Runnable runnable;
// constructor
public CategoryDynamicAdapter(Activity a, Context context, Bitmap [] imagelist,ArrayList<CategoryBean> list) {
this.context = context;
this.categoryList = list;
this.a = a;
}
// Baseadapter to the set the data response from web service into listview.
public BaseAdapter mEventAdapter = new BaseAdapter() {
#Override
public int getCount() {
return categoryList.size();
}
#Override
public Object getItem(int position) {
return categoryList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
class ViewHolder {
TextView title,category,uploadedBy;
ImageView image;
RatingBar video_rating;
Button report_video ,Flag_video;
}
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder vh = null ;
if(convertView == null) {
vh = new ViewHolder();
convertView = LayoutInflater.from(context).inflate (R .layout.custom_category_list_layout,null,false);
vh.title = (TextView) convertView .findViewById (R.id.title);
vh.image = (ImageView) convertView.findViewById(R.id.Imagefield);
convertView.setTag(vh);
}
else
{
vh=(ViewHolder) convertView.getTag();
}
try
{
final CategoryBean Cb = categoryList.get(position);
//pay attention to code below this line i have shown here how to select a listview using arraylist getter setter objects
String checkedStatus = Cb.getCheckedStringStaus();
if(checkdStatus.equal("0")
{
System.out.println("Listview not selected ");
//CK.get(arg2).setChecked(false);
checkBox.setChecked(false);
v.setSelected(false);
}
else ////checkdStatus.equal("1")
{
System.out.println("Listview selected ");
//CK.get(arg2).setChecked(true);
checkBox.setChecked(true);
v.setSelected(true);
}
catch (Exception e)
{
e.printStackTrace();
}