Android toggle button save state custom listview - java

Hello friend i am new in android i want to know how to save ToggleButton state in custom ArrayAdapter i create custom ListView with help of ArrayAdapter now i want how save its state in Adapter here is my code pleae explain what logic used to achieve this goal i am on beginner level don't how to achieve this goal?
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter < String > {
private ALLVERSE activity;
private List < String > versenumber;
private List < String > verseid;
private List < String > verselist;
private List < String > refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean save;
public static final String MyPREFERENCES = "MyPrefs";
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List < String > versenumber, List < String > verselist, List < String > refernce, List < String > verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid = verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
//My toggle button
holder.bookmark.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
} else {
}
}
});
//mDBHelper = new DatabaseHelper(activity);
//mDb = mDBHelper.getWritableDatabase();
//ContentValues contentValues=new ContentValues();
//contentValues.put("id",verseid.get(position));
//contentValues.put("bookname",refernce.get(position));
//contentValues.put("versenumber",versenumber.get(position));
//contentValues.put("verse",verselist.get(position));
//long check=mDb.insert("favourite",null,contentValues);
//Log.d("MY_TAG","DB IS NOW "+check);
//Toasty.success(activity, "Added in favouite"+check, Toast.LENGTH_SHORT, true).show();
holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});
/* holder.removebookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
// long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
//Toasty.error(activity, "Remove in favouite"+delete, Toast.LENGTH_SHORT, true).show();
}
});*/
return convertView;
}
static class ViewHolder {
private ToggleButton favourite;
private TextView versenumber;
private TextView verselist;
private CircleMenu circleMenu;
private ImageView share;
//toggle button
public ToggleButton bookmark;
private boolean defaultvalue;
private ALLVERSE activity;
private ImageView speakverse;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
bookmark = (ToggleButton) v.findViewById(R.id.adbookmark);
speakverse = (ImageView) v.findViewById(R.id.speakverse);
}
}
}

Ideally an adapter is an object to adapt a particular dataset to render a view within a listview. So you should have a data structure (class object) for every row visible in that list view and put it in an array list. Based on the position in getView method, retrieve the data for the row and initialize views from this data. Now this data set can be saved on server or in local memory in any format preferably in JSON and can be retrieved back in future.

Related

SharedPreferences Data spreads on every Fragment

I got a problem with the date of my SharedPreferences. I am using 5 Fragment wher you can dynamically add item to a RecyclerView. The Problem is that when ever I save my data on a particular fragment and reload the app the value that has been saved loads into every single Fragment of mine.It actually save the data to the Fragment it is on.I am using Gson to save my ArrayList of items
This is my Fragment (Fragment0 from 5 in total, the others are just copied and refactored)
package com.example.barryblack;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FragmentPage0 extends Fragment {
private ExampleAdapter mAdapter;
private EditText editTask;
ArrayList<MyItem> items;
private Button insertbtn;
private Button stateButton;
private TextView taskText;
private String task;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable
Bundle savedInstanceState) {
CreateExampleList();
View view = inflater.inflate(R.layout.page_fragment0, container, false);
loadData();
RecyclerView recyclerView = view.findViewById(R.id.listRecyclerView);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(recyclerView);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemViewCacheSize(500);
mAdapter = new ExampleAdapter(items);
recyclerView.setAdapter(mAdapter);
taskText = view.findViewById(R.id.tv_country);
insertbtn = view.findViewById(R.id.button_insert);
editTask = view.findViewById(R.id.editTask);
stateButton = view.findViewById(R.id.tv_button);
insertbtn.setEnabled(false);
editTask.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String taskInput = editTask.getText().toString().trim();
insertbtn.setEnabled(!taskInput.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
task = editTask.getText().toString().trim();
}
});
insertbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InsertItem();
SaveData();
editTask.setText(null);
}
});
return view;
}
private void SaveData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(items);
editor.putString("task list", json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = this.getActivity().getSharedPreferences("shared
preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<MyItem>>() {
}.getType();
items = gson.fromJson(json, type);
if (items == null) {
items = new ArrayList();
}
}
public void InsertItem() {
items.add(new MyItem(task, stateButton));
mAdapter.notifyItemInserted(items.size());
}
private void CreateExampleList() {
items = new ArrayList<MyItem>();
}
ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new ItemTouchHelper.SimpleCallback(0,
ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder
viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
items.remove(viewHolder.getAdapterPosition());
mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());
SaveData();
}
};
}
This is my Adapter. I think the problem is inside the OnCreateViewHolder but im not quiet sure
package com.example.barryblack;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {
private ArrayList<MyItem> mExampleList;
public static class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView mTextView;
private EditText topicName;
public Button mButton;
private int clicks = 1;
public static final String SHARED_PREFS = "sharedPrefs";
public static final String TOPIC = "topic";
public static final String CLICKS = "clicks";
public ExampleViewHolder(View itemView) {
super(itemView);
mTextView = itemView.findViewById(R.id.tv_country);
mButton = itemView.findViewById(R.id.tv_button);
topicName = itemView.findViewById(R.id.editText);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicks++;
if (clicks % 2 == 0) {
mButton.setBackgroundResource(R.drawable.button_green);
}else
mButton.setBackgroundResource(R.drawable.button_red);
}
});
}
}
public ExampleAdapter(ArrayList<MyItem> exampleList) {
mExampleList = exampleList;
}
#Override
public ExampleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.example_item, parent, false);
ExampleViewHolder evh = new ExampleViewHolder(v);
return evh;
}
#Override
public void onBindViewHolder(ExampleViewHolder holder, int position) {
MyItem currentItem = mExampleList.get(position);
holder.mTextView.setText(currentItem.getTaskText());
}
#Override
public int getItemCount() {
return mExampleList.size();
}
}
Use this for your fragments. So every fragment has his own SharedPreferences
private static final String SHARED_PREFS_FRAGMENT_A = "fragmentA";
private static final String SHARED_PREFS_FRAGMENT_B = "fragmentB";
...
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(SHARED_PREFS_FRAGMENT_A , MODE_PRIVATE);

How to use different background color for every listview item

Hello friends I am using a custom listview and this color picker library ' implementation 'petrov.kristiyan:colorpicker-library:1.1.5' here is link library link https://github.com/kristiyanP/colorpicker my problem is that when any user click on any particular item in the listview the color dialog is popped up so user can pick color in this dialog box and change background color of a particular item which successfully I done. But my problem is that how I can save this state for later used here is my picture you get idea what actually i want?
here my picture
here is picture of highlight two item with different color
how can save the state ?
my custom adopter code
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int selectcolor;
ArrayList<String>colors;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//check if id is exits in db
if(CheckIsDataAlreadyInDBorNot("highlight","verseid",verseid.get(position)))
{
if(verseid.get(position).equals(verseid.get(position))){
}
}
else {
}
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.linearLayout.setBackgroundColor(selectcolor);
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("highlight","verseid=?",new String[]{verseid.get(position)});
Toast.makeText(activity, "Remove highlight", Toast.LENGTH_SHORT).show();
}
});
//here color picker dialog popup for chosing color
holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("verseid",verseid.get(position));
long check=mDb.insert("highlight",null,contentValues);
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
//id get
Toast.makeText(activity, ""+verseid.get(position), Toast.LENGTH_SHORT).show();
//postion
//Toast.makeText(activity, ""+getItemId(position), Toast.LENGTH_SHORT).show();
ColorPicker colorPicker = new ColorPicker(activity);
colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
holder.linearLayout.setBackgroundColor(color);
}
#Override
public void onCancel() {
}
}).show();
return false;
}
});
/*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
return false;
}
});*/
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
//add in favourite
holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Log.d("MY_TAG","DB IS NOW "+check);
Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}else {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
/* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
*/
//My toggle button
/* holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ToggleButton addfavoruite;
private ImageView speakverse;
private LinearLayout linearLayout;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
/*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)v.findViewById(R.id.layout);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
}
I would suggest to have all your item properties in one object and add the background color to it.
When a color is picked just save it to your verse object and when view is created set it.
Also add the background to your ViewHolder.
public class Verse {
private String versenumber;
private String verseid;
private String verselist;
private String refernce;
private int backgroundColor
// Getters and setters
}
public class FullverseAdopter extends ArrayAdapter<Verse> {
private ALLVERSE activity;
private List<Verse> verse;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int selectcolor;
ArrayList<String>colors;
public FullverseAdopter(ALLVERSE context, int resource, List<Verse> verse) {
super(context, resource);
this.activity = context;
this.verse = verse;
}
// The rest of your code
}

OnClickListener doesn't work in custom listview

I try to use OnClickListener in custom listview,But when textview clicked (Onclicklistener Run) It's runing code on several textview in listview!
see holder.tvComment.setOnClickListener in My ListAdapter.class Updated:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.skyline.jimmy.widget.LikeToast;
import com.skyline.jimmy.widget.MyToast;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
//import android.text.ClipboardManager;
import android.content.ClipboardManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class VoteListAdapter extends BaseAdapter {
protected static final String CLIPBOARD_SERVICE = null;
private final String TAG = "*** VoteListAdapter ***";
private Context context;
private ArrayList<Vote> votes;
int showHideBtn = 0;
public VoteListAdapter(Context context,List<Vote> voteList) {
this.context =context;
this.votes =(ArrayList<Vote>) voteList;
}
#Override
public int getCount() {
return votes.size();
}
#Override
public Object getItem(int position) {
return votes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.row, null);
holder.tvName = (TextView) convertView.findViewById(R.id.user);
holder.tvComment = (TextView) convertView.findViewById(R.id.tvComment);
holder.tvDate = (TextView) convertView.findViewById(R.id.tDate);
holder.tvLikes = (TextView) convertView.findViewById(R.id.tvLikes);
holder.ratingBar = (RatingBar)convertView.findViewById(R.id.ratingBar);
holder.share = (ImageButton) convertView.findViewById(R.id.sharebtn);
holder.copyJoke = (ImageButton) convertView.findViewById(R.id.copyJoke);
holder.btnLike = (Button) convertView.findViewById(R.id.likebtn);
holder.btnLiked = (Button) convertView.findViewById(R.id.likedbtn);
holder.btns = (ImageButton) convertView.findViewById(R.id.btns);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Typeface yaghut=Typeface.createFromAsset(context.getAssets(), "font/Far_Casablanca.ttf");
String likes = Integer.parseInt(votes.get(position).getRate()) + " likes";
holder.tvName.setText(votes.get(position).getName());
holder.tvComment.setText(votes.get(position).getComment());
holder.tvDate.setText(getFormatedDate(votes.get(position).getPublishDate()));
holder.tvLikes.setText(likes);
holder.ratingBar.setRating(Integer.parseInt(votes.get(position).getRate()));
holder.tvComment.setTypeface(yaghut);
if (convertView == null) {
holder.tvComment.setOnClickListener( new OnClickListener() {
int clicks = 0;
#Override
public void onClick(View v) {
clicks = clicks + 1;
if(clicks == 1){
}else if(clicks == 2) {
LikeToast.makeText(context, "Liked" , Toast.LENGTH_SHORT).show();
holder.btnLike.setText("Liked");
Drawable image = context.getResources().getDrawable( R.drawable.ic_action_liked );
int hlike = image.getIntrinsicHeight();
int wlike = image.getIntrinsicWidth();
image.setBounds( 0, 0, wlike, hlike );
holder.btnLike.setCompoundDrawables( image, null, null, null );
//holder.btnLikes.setBackgroundDrawable(R.drawable.ic_action_liked);
} else{
clicks = 2;
}
}
});
convertView.setTag(holder);
}
holder.btns.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
if(showHideBtn == 1){
holder.share.setVisibility(View.INVISIBLE);
holder.btns.setVisibility(View.VISIBLE);
holder.copyJoke.setVisibility(View.INVISIBLE);
showHideBtn = 0;
} else {
holder.share.setVisibility(View.VISIBLE);
holder.btns.setVisibility(View.VISIBLE);
holder.copyJoke.setVisibility(View.VISIBLE);
showHideBtn = 1;
}
}
});
holder.copyJoke.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
String Joke = votes.get(position).getComment();
clipboard.setText(Joke);
Toast toast3 = MyToast.makeText(context, "جک مورد نظر کپی شد", Toast.LENGTH_SHORT);
toast3.show();
}
});
holder.share.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
/* Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,votes.get(position).getComment());
try {
context.startActivity(Intent.createChooser(i, "Share"));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
*/
Toast toast = MyToast.makeText(context, "این قسمت در نسخه بتا در حال طراحی است", Toast.LENGTH_LONG);
toast.show();
Toast toast2 = MyToast.makeText(context, "منتظر آپدیت باشید", Toast.LENGTH_SHORT);
toast2.show();
}
});
return convertView;
}
private String getFormatedDate(String date) {
String myDate = null;
try {
Date oldDate = new SimpleDateFormat("yy-mm-dd hh:mm:ss").parse(date);
myDate = new SimpleDateFormat("dd MMM yyyy").format(oldDate);
} catch (ParseException e) {
myDate = "";
e.printStackTrace();
}
return myDate;
}
static class ViewHolder {
ImageButton copyJoke;
ImageButton share;
ImageButton btns;
Button btnLike;
Button btnLiked;
TextView tvName;
TextView tvLikes;
TextView tvComment;
TextView tvDate;
RatingBar ratingBar;
}
}
write your setOnClickListener code into the if condition
if (convertView == null) {
.....
.....
// write here your holder.tvComment.setOnClickListener
convertView.setTag(holder);
}
and before this line:
convertView.setTag(holder);
Your full adapter would be something like this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.skyline.jimmy.widget.LikeToast;
import com.skyline.jimmy.widget.MyToast;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
//import android.text.ClipboardManager;
import android.content.ClipboardManager;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class VoteListAdapter extends BaseAdapter {
ViewHolder holder;
protected static final String CLIPBOARD_SERVICE = null;
private final String TAG = "*** VoteListAdapter ***";
private Context context;
private ArrayList<Vote> votes;
int showHideBtn = 0;
public VoteListAdapter(Context context,List<Vote> voteList) {
this.context =context;
this.votes =(ArrayList<Vote>) voteList;
}
#Override
public int getCount() {
return votes.size();
}
#Override
public Object getItem(int position) {
return votes.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.row, null);
holder.tvName = (TextView) convertView.findViewById(R.id.user);
holder.tvComment = (TextView) convertView.findViewById(R.id.tvComment);
holder.tvDate = (TextView) convertView.findViewById(R.id.tDate);
holder.tvLikes = (TextView) convertView.findViewById(R.id.tvLikes);
holder.ratingBar = (RatingBar)convertView.findViewById(R.id.ratingBar);
holder.share = (ImageButton) convertView.findViewById(R.id.sharebtn);
holder.copyJoke = (ImageButton) convertView.findViewById(R.id.copyJoke);
holder.btnLike = (Button) convertView.findViewById(R.id.likebtn);
holder.btnLiked = (Button) convertView.findViewById(R.id.likedbtn);
holder.btns = (ImageButton) convertView.findViewById(R.id.btns);
holder.btns.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
if(showHideBtn == 1){
holder.share.setVisibility(View.INVISIBLE);
holder.btns.setVisibility(View.VISIBLE);
holder.copyJoke.setVisibility(View.INVISIBLE);
showHideBtn = 0;
} else {
holder.share.setVisibility(View.VISIBLE);
holder.btns.setVisibility(View.VISIBLE);
holder.copyJoke.setVisibility(View.VISIBLE);
showHideBtn = 1;
}
}
});
holder.copyJoke.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
String Joke = votes.get(position).getComment();
clipboard.setText(Joke);
Toast toast3 = MyToast.makeText(context, "جک مورد نظر کپی شد", Toast.LENGTH_SHORT);
toast3.show();
}
});
holder.share.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
/* Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,votes.get(position).getComment());
try {
context.startActivity(Intent.createChooser(i, "Share"));
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
*/
Toast toast = MyToast.makeText(context, "این قسمت در نسخه بتا در حال طراحی است", Toast.LENGTH_LONG);
toast.show();
Toast toast2 = MyToast.makeText(context, "منتظر آپدیت باشید", Toast.LENGTH_SHORT);
toast2.show();
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Typeface yaghut=Typeface.createFromAsset(context.getAssets(), "font/Far_Casablanca.ttf");
String likes = Integer.parseInt(votes.get(position).getRate()) + " likes";
holder.tvName.setText(votes.get(position).getName());
holder.tvComment.setText(votes.get(position).getComment());
holder.tvDate.setText(getFormatedDate(votes.get(position).getPublishDate()));
holder.tvLikes.setText(likes);
holder.ratingBar.setRating(Integer.parseInt(votes.get(position).getRate()));
holder.tvComment.setTypeface(yaghut);
return convertView;
}
private String getFormatedDate(String date) {
String myDate = null;
try {
Date oldDate = new SimpleDateFormat("yy-mm-dd hh:mm:ss").parse(date);
myDate = new SimpleDateFormat("dd MMM yyyy").format(oldDate);
} catch (ParseException e) {
myDate = "";
e.printStackTrace();
}
return myDate;
}
static class ViewHolder {
ImageButton copyJoke;
ImageButton share;
ImageButton btns;
Button btnLike;
Button btnLiked;
TextView tvName;
TextView tvLikes;
TextView tvComment;
TextView tvDate;
RatingBar ratingBar;
}
}

How to add a listview item to a whole other listview

So in my android app, I have two scrollable tabs which each contain Listview using a Fragment. One a list of apps and the other is blank. What I am aiming to do is add a plus button in place of where my checkbox is and duplicate that item in the other listview which is blank.
I have done research on this, but I have not found any successful examples on how to implement this.
Android - Add an item from one ListView to another ListView?
Here is my fragment that returns the apps
package com.spicycurryman.getdisciplined10.app;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.ibc.android.demo.appslist.app.ApkAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class InstalledAppActivity extends Fragment
implements OnItemClickListener {
PackageManager packageManager;
ListView apkList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.user_installed, container, false);
packageManager = getActivity().getPackageManager();
/*To filter out System apps*/
apkList = (ListView) rootView.findViewById(R.id.applist);
new LoadApplications(getActivity().getApplicationContext()).execute();
return rootView;
}
/**
* Return whether the given PackageInfo represents a system package or not.
* User-installed packages (Market or otherwise) should not be denoted as
* system packages.
*
* #param pkgInfo
* #return boolean
*/
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
private boolean isSystemPackage1(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
: true;
}
// Don't need in Fragment
/*#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.block, menu);
// super.onCreateOptionsMenu(menu,inflater);
}*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
Context mContext;
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
/* List<ApplicationInfo> list = mContext.getPackageManager().getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for(int n = 0;n<list.size();n++){
if ((list.get(n).flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP))
}*/
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this.getActivity());
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(getActivity(), packageList1, packageManager));
if (pDialog.isShowing()){
pDialog.dismiss();
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
And here is my adapter class:
package com.ibc.android.demo.appslist.app;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import com.spicycurryman.getdisciplined10.app.R;
import java.util.List;
public class ApkAdapter extends BaseAdapter {
List<PackageInfo> packageList;
Activity context;
PackageManager packageManager;
boolean[] itemChecked;
public ApkAdapter(Activity context, List<PackageInfo> packageList,
PackageManager packageManager) {
super();
this.context = context;
this.packageList = packageList;
this.packageManager = packageManager;
itemChecked = new boolean[packageList.size()];
}
private class ViewHolder {
TextView apkName;
CheckBox ck1;
}
public int getCount() {
return packageList.size();
}
public Object getItem(int position) {
return packageList.get(position);
}
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.installed_apps, null);
holder = new ViewHolder();
holder.apkName = (TextView) convertView
.findViewById(R.id.appname);
holder.ck1 = (CheckBox) convertView
.findViewById(R.id.checkBox1);
convertView.setTag(holder);
//holder.ck1.setTag(packageList.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
PackageInfo packageInfo = (PackageInfo) getItem(position);
Drawable appIcon = packageManager
.getApplicationIcon(packageInfo.applicationInfo);
String appName = packageManager.getApplicationLabel(
packageInfo.applicationInfo).toString();
appIcon.setBounds(0, 0, 75, 75);
holder.apkName.setCompoundDrawables(appIcon, null, null, null);
holder.apkName.setCompoundDrawablePadding(15);
holder.apkName.setText(appName);
holder.ck1.setChecked(false);
if (itemChecked[position])
holder.ck1.setChecked(true);
else
holder.ck1.setChecked(false);
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.ck1.isChecked())
itemChecked[position] = true;
else
itemChecked[position] = false;
}
});
return convertView;
}
}
How would I go about achieving this?
So what you are doing is, you are populating a listview of installed apps using package manager. Add a plus button in place of the checkbox. Now get installed apps similar to this -
List<PackageInfo> packageList1 = packageManager.getInstalledPackages(0);
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
for (int i = 0; i < packageList1.size(); i++) {
PackageInfo PackInfo = packageList1.get(i);
if (((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) {
//Add to adapter
}
}
}
Now, create a public string array in the activity which is holding the tabs. When you click on the plus button add the packagename to the array.
Now on the other tab use the same adapter, but here before adding it to the adapter check if it is found in the string array using the index. Something like -
List<PackageInfo> packageList1 = packageManager.getInstalledPackages(0);
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
for (int i = 0; i < packageList1.size(); i++) {
PackageInfo PackInfo = packageList1.get(i);
if (((PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true) {
if (Mainactivity.array contains String PackageName= PackInfo.packageName)
{
//Add to adapter
}
}
}
}
To persist the selected apps, add their package name to shared_preferences.
edit :
In your fragment's LoadApplications class, you retrieve a list of installed apps. On the second fragment use the same code, but just add one more condition
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
if (array contains packagename){
packageList1.add(pi);
}
}
List<UserApps> packageListBlocked = new ArrayList<UserApps>();
holder.ck1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (holder.ck1.isChecked())
itemChecked[position] = true;
packageListBlocked.add(packageList.get(position));
else
itemChecked[position] = false;
}
});
ArrayList can hold duplicate data, so be cautious while adding.
Now you have all checkedItems in packageListBlocked pass it on to next tab and set data, make sure you call adapter.notifyDataSetChanged();

Android Beginner: ListView with Images and CheckBoxes

I am a beginner programmer so please bear with me. I have been able to create a listview with images in it and thought I could modify it to add a checkbox. However, this setup does not work. Any suggestions to how I may fix my code to create a listview with both an image and checkbox?
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CheckboxList extends ListActivity{
private LayoutInflater mInflater;
private Vector<RowData> data;
RowData rd;
static CheckBox box0,box1,box2,box3;
static final String[] title = new String[] {
"Box 1", "Box 2",
"Box 3 ","Box 4" };
static final CheckBox[] boxes= new CheckBox[] {box0,box1,box2,box3};
private Integer[] imgid = {
R.drawable.magnum,R.drawable.mg,R.drawable.mk,
R.drawable.mk46};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mInflater = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
data = new Vector<RowData>();
for(int i=0;i<title.length;i++){
try {
rd = new RowData(i,title[i],boxes[i]);
} catch (ParseException e) {
e.printStackTrace();
}
data.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.check_list,
R.id.title, data);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position,
long id) {
Toast.makeText(getApplicationContext(), "You have selected "
+(position+1)+"th item", Toast.LENGTH_SHORT).show();
}
private class RowData {
protected int mId;
protected String mTitle;
protected CheckBox mCBox;
RowData(int id,String title,CheckBox cbox){
mId=id;
mTitle = title;
mCBox=cbox;
}
#Override
public String toString() {
return mId+" "+mTitle+" "+mCBox;
}
}
private class CustomAdapter extends ArrayAdapter<RowData> {
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects) {
super(context, resource, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
TextView title = null;
CheckBox box = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView){
convertView = mInflater.inflate(R.layout.check_list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
title = holder.gettitle();
title.setText(rowData.mTitle);
box = holder.getcheckbox();
box.setChecked(false);
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
return convertView;
}
private class ViewHolder {
private View mRow;
private TextView title = null;
private CheckBox cbox = null;
private ImageView i11=null;
public ViewHolder(View row) {
mRow = row;
}
public TextView gettitle() {
if(null == title){
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public CheckBox getcheckbox() {
if(null == cbox){
cbox = (CheckBox) mRow.findViewById(R.id.checkBox);
}
return cbox;
}
public ImageView getImage() {
if(null == i11){
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
} }
Look at this links.it may helpfull......
http://www.vogella.com/articles/AndroidListView/article.html
CustomListview With Images and Checkboxes Example

Categories