I have created a custom listview with a checkbox and two line of text. I want to change the checkbox state when I click on the list item (this means that if I click any part of the list item checkbox or text, checkbox will change state).
To achieve this I have added this in the custom_list_row xml file:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants" >
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:clickable="false" />
and in the java class I did these:
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final CheckBox checkBox;
checkBox = (CheckBox)view.findViewById(R.id.checkbox);
if(checkBox.isChecked()){
checkBox.setChecked(false);
}
else {
checkBox.setChecked(true);
}
}
});
This works fine. But the only problem is that when I select some items and scroll down-->the go back to the selected items-->the selected items becomes unselected.
I did not do anything with setOnCheckedChangeListener
What went wrong? Any suggestion to solve this problem will be helpful.
Thanks
Please make change while checkbox is select/unselect
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final CheckBox checkBox;
checkBox = (CheckBox)view.findViewById(R.id.checkbox);
if(checkBox.isChecked()){
checkBox.setChecked(false);
// Reset the checkbox in array list/Bean like
list.set(); // set new value of list
adapter.notifyChange();
}
else {
checkBox.setChecked(true);
// Reset the checkbox in array list/Bean like
list.set(); // set new value of list
adapter.notifyChange();
}
}
});
This change solve this issue of mine.
I suggest that you need to use recyclerview
public class CardViewActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Student> studentList;
private Button btnSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
btnSelection = (Button) findViewById(R.id.btnShow);
studentList = new ArrayList<Student>();
for (int i = 1; i <= 15; i++) {
Student st = new Student("Student " + i, "androidstudent" + i
+ "#gmail.com", false);
studentList.add(st);
}
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Students");
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// create an Object for Adapter
mAdapter = new CardViewDataAdapter(studentList);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
btnSelection.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = "";
List<Student> stList = ((CardViewDataAdapter) mAdapter)
.getStudentist();
for (int i = 0; i < stList.size(); i++) {
Student singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
data = data + "\n" + singleStudent.getName().toString();
/*
* Toast.makeText( CardViewActivity.this, " " +
* singleStudent.getName() + " " +
* singleStudent.getEmailId() + " " +
* singleStudent.isSelected(),
* Toast.LENGTH_SHORT).show();
*/
}
}
Toast.makeText(CardViewActivity.this,
"Selected Students: \n" + data, Toast.LENGTH_LONG)
.show();
}
});
}
}
For more see http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
OR
If you want to use listview try this way
public class CustomAdapter extends BaseAdapter {
private final LayoutInflater inflater;
private final Context context;
private List<Modelclass> listData;
public CustomAdapter(Context mainActivity, List<Modelclass> listData) {
context = mainActivity;
this.listData = listData;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item_poojaselection, null);
holder.tv = (TextView) convertView.findViewById(R.id.list_item_poojaname);
holder.checks = (CheckBox) convertView.findViewById(R.id.list_item_poojacheck);
convertView.setTag(holder);
}else {
holder = (ViewHolder) convertView.getTag();
}
holder.checks.setOnCheckedChangeListener(null);
holder.checks.setFocusable(false);
if (listData.get(position).isselected) {
holder.checks.setChecked(true);
} else {
holder.checks.setChecked(false);
}
holder.checks.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton cb, boolean b) {
if (checkMaxLimit()) {
if (listData.get(position).isselected && b) {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
} else {
holder.checks.setChecked(false);
listData.get(position).isselected = false;
Toast.makeText(context, "Max limit reached", Toast.LENGTH_SHORT).show();
}
} else {
if (b) {
listData.get(position).isselected = true;
} else {
listData.get(position).isselected = false;
}
}
}
});
holder.tv.setText(listData.get(position).getLISTING_NAME());
return convertView;
}
public boolean checkMaxLimit() {
int countermax = 0;
for(Modelclass item : listData){
if(item.isselected){
countermax++;
}
}
return countermax >= 5;
}
public class ViewHolder {
TextView tv;
public CheckBox checks;
}
}
Related
I have a fragment with a listView.
The view is populated from a remote received JSON array as follows:
private void callVolley(){
SharedPreferences prefs3 =
getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);
final String id_materia= "42";
final String num_examen= "787878";
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Cargando temas de la materia seleccionada...");
showDialog();
JsonArrayRequest jArr = new JsonArrayRequest(url+"?id="+id_materia, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// list.invalidateViews();
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(jArr);
}
Then I add programmatically a checkbox to each list item.
This is the adapter:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
At start I need all checkboxes to be checked.
Then the user can check/uncheck the desired items.
On the fragment there is a button that reads all items checkbox states.
What should I implement to put all items in status checked so that on button clicked all items are recognized as checked?
This is a screenshot at start with all items unchecked:
EDIT
Code for the button onClickListener in the fragment:
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkbox = "";
checkbox_id = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
checkbox_id += hold.getId()+",";
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
String preguntas = checkbox_id;
mPref = getActivity().getSharedPreferences(MIEXAMEN, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mPref.edit();
editor.putString("preguntas_numero_string",preguntas);
editor.putString("preguntas_string",dipilih);
Log.d("seleccion","seleccion preguntas "+preguntas);
Log.d("seleccion","seleccion dipilih "+dipilih);
editor.apply();
} else {
dipilih = "No has seleccionado ningĂșn tema.";
}
formSubmit(dipilih);
}
});
Do the following changes:
When you are adding Data to the list of Data.
Data item = new Data();
item.setMenu(obj.getString(TAG_NOMBRE));
item.setId(obj.getString(TAG_ID));
item.setCheckbox(true)
itemList.add(item);
This will initially make the checkbox checked.
Edit:
Update your xml layout. in your CheckBox put this attribute.
android:clickable="false"
Update your list setOnItemClickListener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setCheckBox(position);
}
});
Try replacing with the below code
viewHolder.checkBox.setChecked(true);
instead of
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
Use this. It should work. -
Initially this -
viewHolder.checkBox.setChecked(true);
Then
viewHolder.checkBox.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton
buttonView,boolean isChecked) {
if(isChecked){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
}
}
);
I am following a tutorial about multiple choice listview in android.
When executing the app, the listview shows some items, not all of them. After clicking on the listview, it shows all items.
I want to know where is the reason of that issue.
This is the code for MainActivity class:
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
FloatingActionButton fab;
ListView list;
TextView txt_menu;
String dipilih;
private static final String TAG = MainActivity.class.getSimpleName();
Adapter adapter;
ProgressDialog pDialog;
List<Data> itemList = new ArrayList<Data>();
// Sesuaikan dengan IP Address PC/LAptop atau ip emulator bawaan android 10.0.2.2
private static String url = "https://.../test/menu.php";
public static final String TAG_NAMA = "nama";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
list = (ListView) findViewById(R.id.list_menu);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String checkbox = "";
for (Data hold : adapter.getAllData()) {
if (hold.isCheckbox()) {
checkbox += "\n" + hold.getMenu();
}
}
if (!checkbox.isEmpty()) {
dipilih = checkbox;
} else {
dipilih = "Anda Belum Memilih Menu.";
}
formSubmit(dipilih);
}
});
callVolley();
adapter = new Adapter(this, (ArrayList<Data>) itemList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
}
private void formSubmit(String hasil){
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View dialogView = inflater.inflate(R.layout.form_submit, null);
dialog.setView(dialogView);
dialog.setIcon(R.mipmap.ic_launcher);
dialog.setTitle("Menu Yang Dipilih");
dialog.setCancelable(true);
txt_menu = (TextView) dialogView.findViewById(R.id.txt_menu);
txt_menu.setText(hasil);
dialog.setNeutralButton("CLOSE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void callVolley(){
itemList.clear();
// menapilkan dialog loading
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
showDialog();
// membuat request JSON
JsonArrayRequest jArr = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hideDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Data item = new Data();
item.setMenu(obj.getString(TAG_NAMA));
// menambah item ke array
itemList.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifikasi adanya perubahan data pada adapter
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideDialog();
}
});
// menambah request ke request queue
AppController.getInstance().addToRequestQueue(jArr);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
And this is the Adapter class:
public class Adapter extends BaseAdapter {
private Context activity;
private ArrayList<Data> data;
private static LayoutInflater inflater = null;
private View vi;
private ViewHolder viewHolder;
public Adapter(Context context, ArrayList<Data> items) {
this.activity = context;
this.data = items;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
viewHolder.menu.setText(items.getMenu());
}
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
public ArrayList<Data> getAllData(){
return data;
}
public void setCheckBox(int position){
Data items = data.get(position);
items.setCheckbox(!items.isCheckbox());
notifyDataSetChanged();
}
public class ViewHolder{
TextView menu;
CheckBox checkBox;
}
}
If you need other code parts to detect the problem, please let me know.
EDIT
First launch
After clicking on the listview
The problem is this bit of your code in your adapter's getView() callback:
if(view == null) {
...
}else {
...
viewHolder.menu.setText(items.getMenu());
}
What's happening here is that you're only caling setText() when the item view is recycled by the ListView. The reason everything shows up after you click a checkbox is that the ListView rebinds everything when you call notifyDataSetChanged().
You should call this method outside of the if/else statement so that it is executed every time.
if(view == null) {
...
}else {
...
}
viewHolder.menu.setText(items.getMenu());
I think the issue you are having is coming from the getView() method in your Adapter class.
Since you are using a ViewHolder to recycle objects you are first checking if the exist first before creating them if(view == null). But, you are only creating them and not assigning the TextView objects a String value. You only do that once the object has already been created. So, when you click on an item, you are calling notifyDataSetChanged causing the list to be updated. Then the values are set in the `TextView.
So try this instead: put the line viewHolder.menu.setText(items.getMenu()); outside the conditional statement:
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
vi = view;
final int pos = position;
Data items = data.get(pos);
if(view == null) {
vi = inflater.inflate(R.layout.list_row, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) vi.findViewById(R.id.cb);
viewHolder.menu = (TextView) vi.findViewById(R.id.nama_menu);
vi.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.menu.setText(items.getMenu());
if(items.isCheckbox()){
viewHolder.checkBox.setChecked(true);
} else {
viewHolder.checkBox.setChecked(false);
}
return vi;
}
try this once
adapter = new Adapter(this, (ArrayList) itemList);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
adapter.setCheckBox(position);
}
});
list.setAdapter(adapter);
}
set adapter at the end
setContentView(R.layout.activity_violation);
db = new DatabaseHelper(this);
sqLiteDatabase = db.getReadableDatabase();
spinner = (Spinner) findViewById(R.id.spinner1);
loadspinnerdata();
txtTexts = (TextView) findViewById(R.id.texts);
btnBack = (Button) findViewById(R.id.btnBack);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listviewData();
}
});
strSelectedItem = spinner.getSelectedItem().toString();
listview = (ListView) findViewById(R.id.listView);
LayoutInflater inflater = getLayoutInflater();
ViewGroup header = (ViewGroup) inflater.inflate(R.layout.list_header, listview, false);
listview.addHeaderView(header, null, false);
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list_query = "select _id,section,offence,fine from tblSection";
Cursor clistview = sqLiteDatabase.rawQuery(list_query, null);
listadapter = new ListAdapter(this, clistview, 0);
listview.setAdapter(listadapter);private void listviewData() {
int cntChoice = listview.getCount();
String checked = "";
String unchecked = "";
SparseBooleanArray sparseBooleanArray = listview.getCheckedItemPositions();
for(int i = 0; i < cntChoice; i++)
{
if(sparseBooleanArray.get(i))
{
checked += listview.getItemAtPosition(i).toString() + "\n";
}
else if(!sparseBooleanArray.get(i))
{
unchecked+= listview.getItemAtPosition(i).toString() + "\n";
}
}
I am using cursorAdapter in order to populate listview from database?so I am not getting position as i get from getView method in arrayAdapter
public class ListAdapter extends CursorAdapter{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
ArrayAdapter<String> objects;
private boolean chkItem;
CompoundButton.OnCheckedChangeListener myCheckChangList;
public ListAdapter(Context context, Cursor c, int _id) {
super(context, c,_id);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.listview_item,viewGroup,false);
}
public class ViewHolder{
TextView tvSection,tvOffence,tvId,tvFine;
CheckBox chkBox;
boolean chkItem;
boolean selected = false;
public ViewHolder(boolean chkItem){
super();
this.chkItem=chkItem;
}
public ViewHolder() {
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder=null;
holder = new ViewHolder();
holder.tvSection = (TextView) view.findViewById(R.id.txtSection);
holder.tvOffence = (TextView) view.findViewById(R.id.txtOffence);
holder.tvId = (TextView) view.findViewById(R.id.txtId);
holder.tvFine = (TextView) view.findViewById(R.id.txtFine);
holder.chkBox = (CheckBox) view.findViewById(R.id.checkBox);
holder.chkBox.setOnCheckedChangeListener(myCheckChangList);
view.setTag(holder);
strFine=cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String strSection = cursor.getString(cursor.getColumnIndexOrThrow("section"));
String strOffence = cursor.getString(cursor.getColumnIndexOrThrow("offence"));
int strFine = cursor.getInt(cursor.getColumnIndexOrThrow("fine"));
holder.tvSection.setText(strSection);
holder.tvOffence.setText(strOffence);
holder.tvFine.setText(String.valueOf(strFine));
final ViewHolder finalHolder = holder;
}
I tried this but this isn't working.I tried checkbox.setOnclicklistener which gives me the checked row value single item but not multiple checked item.I tried sparseboolean array also.
If you are trying to get selected values from listing using checkbox,try this way it will work
public class CardViewActivity extends AppCompatActivity {
private Toolbar toolbar;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<Student> studentList;
private Button btnSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
btnSelection = (Button) findViewById(R.id.btnShow);
studentList = new ArrayList<Student>();
for (int i = 1; i <= 15; i++) {
Student st = new Student("Student " + i, "androidstudent" + i
+ "#gmail.com", false);
studentList.add(st);
}
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Android Students");
}
mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
// create an Object for Adapter
mAdapter = new CardViewDataAdapter(studentList);
// set the adapter object to the Recyclerview
mRecyclerView.setAdapter(mAdapter);
btnSelection.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = "";
List<Student> stList = ((CardViewDataAdapter) mAdapter)
.getStudentist();
for (int i = 0; i < stList.size(); i++) {
Student singleStudent = stList.get(i);
if (singleStudent.isSelected() == true) {
data = data + "\n" + singleStudent.getName().toString();
/*
* Toast.makeText( CardViewActivity.this, " " +
* singleStudent.getName() + " " +
* singleStudent.getEmailId() + " " +
* singleStudent.isSelected(),
* Toast.LENGTH_SHORT).show();
*/
}
}
Toast.makeText(CardViewActivity.this,
"Selected Students: \n" + data, Toast.LENGTH_LONG)
.show();
}
});
}
}
http://android-pratap.blogspot.in/2015/01/recyclerview-with-checkbox-example.html
On clicking outside the adapter, use the following code. "ListAdapter" should be the Adapter class name.
ListAdapter.unCheck((ViewGroup)view.getParent());
If your on clicking is inside the adapter, then ignore the above code and use the below one.
unCheck((ViewGroup)view.getParent());
make the following function in Adapter.
public static void unCheck(ViewGroup vg) {
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
if (v instanceof CheckBox) {
((CheckBox) v).setChecked(true);
} else if (v instanceof ViewGroup) {
unCheck((ViewGroup) v);
}
}
}
The above function will checked all the checkBox of the list view. Have Fun. Take Care.
I am having a listview and it has one checkbox and two textfields , i would like to change check box visibility properties from listview on click funtion, i am able to change the properties from inside the getView funtion but i want it from listview click. Help me find a solution
public class HelpList extends Fragment {
amfFunctions amf;
MyCustomAdapter dataAdapter = null;
Database_Contact contact = new Database_Contact();
DBHelper mydb = new DBHelper(getActivity());
public static final int PICK_CONTACT = 1;
public String user_phone_number;
public String buddyName;
public String buddyNum;
LayoutInflater vi;
View v ;
Fragment fragment = null;
Button myAddButton,myDelButton;
int selected = 0;
Boolean isInternetPresent = false;
ConnectionDetector cd;
ArrayList<Database_Contact> selectedList = new ArrayList<>();
Database_Contact addcontacts = new Database_Contact();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_helplist, container, false);
// Inflate the layout for this fragment
displayListView();
cd = new ConnectionDetector(getActivity());
myDelButton = (Button)v. findViewById(R.id.deleteContact);
myDelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
DeleteContact();
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_SHORT).show();
}
}
});
Constants.i = 0;
myAddButton = (Button)v. findViewById(R.id.Addanother);
myAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
isInternetPresent = cd.isConnectingToInternet();
Log.e("Myaddbutton text ", (String) myAddButton.getText());
if (isInternetPresent) {
if (myAddButton.getText().equals("Close")){
Toast.makeText(getActivity(),
getString(R.string.click_to_close), Toast.LENGTH_SHORT).show();
}
else{
AddContact();
}
}
else{
Toast.makeText(getActivity(),
getString(R.string.nointernet), Toast.LENGTH_LONG).show();
}
}
});
return v;
}
private void displayListView() {
mydb = new DBHelper(getActivity());
ArrayList<Database_Contact> contactlist = (ArrayList<Database_Contact>)
mydb.getAllDatabase_Contacts();
Collections.sort(contactlist, new Comparator<Database_Contact>() {
#Override
public int compare(Database_Contact lhs, Database_Contact rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
//create an ArrayAdaptar from the String Array
dataAdapter = new MyCustomAdapter(getActivity(),
R.layout.activity_allcontactlist, contactlist);
ListView listView = (ListView)v.findViewById(R.id.helplistview);
// Assign adapter to ListView
listView.setTextFilterEnabled(true);
listView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact)
parent.getItemAtPosition(position);
contact.isSelected();
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Database_Contact> {
private ArrayList<Database_Contact> contactlist;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Database_Contact> contactlist) {
super(context, textViewResourceId, contactlist);
this.contactlist = new ArrayList<Database_Contact>();
this.contactlist.addAll(contactlist);
}
private class ViewHolder {
TextView code;
TextView Number;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
vi = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.activity_allcontactlist,
null);
holder = new ViewHolder();
holder.code = (TextView)
convertView.findViewById(R.id.helplist_name);
holder.Number = (TextView)
convertView.findViewById(R.id.helplist_num);
holder.name = (CheckBox)
convertView.findViewById(R.id.checkbox_all);
convertView.setTag(holder);
final ViewHolder finalHolder = holder;
final ViewHolder finalHolder1 = holder;
holder.code.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.Number.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (finalHolder1.name.isShown() == false){
Constants.i = Constants.i+1;
myDelButton.setEnabled(true);
finalHolder.name.setVisibility(View.VISIBLE);
}
else if(finalHolder1.name.isShown() == true) {
finalHolder.name.setVisibility(View.GONE);
Constants.i = Constants.i-1;
if (Constants.i == 0){
myDelButton.setEnabled(false);
}
}
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
Database_Contact contact = (Database_Contact)
cb.getTag();
contact.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Database_Contact contact = contactlist.get(position);
holder.code.setText(contact.getName());
holder.Number.setText(contact.getPhoneNumber());
holder.name.setText("");
holder.name.setChecked(contact.isSelected());
holder.name.setTag(contact);
return convertView;
}
}
}
As I could not find any perfect solution i tried it in a different manner alough its a bit diffenrt from what i wanted i.e on click i used my displayListView() funtion and got the work done
ischeckboxVisible = true;
Runnable run = new Runnable() {
#Override
public void run() {
displayListView();
}
};
getActivity().runOnUiThread(run);
and coming to getView i have used:
if (!ischeckboxVisible)
{
holder.name.setVisibility(View.GONE);
}
if (ischeckboxVisible)
{
holder.name.setVisibility(View.VISIBLE);
}
so every time i do the click it changes the ischeckboxVisible to either true or false and initializes the displatListview() and it works.
I have had help from here Android hide and show checkboxes in custome listview on button click
Hope this might come in handy for some one out there.
Please check below code if it helps you,
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Database_Contact contact = (Database_Contact) contactlist.get(position);
contact.setSelected(!contact.isSelected());
if(contact.isSelected())
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.VISIBLE);
}
else
{
((CheckBox) view.findViewById(R.id.checkbox_all)).setVisibility(View.GONE);
}
}
});
Hello Everyone!!
I am making a sample shopping cart in which i need to get the position of item clicked and get the image displayed on the page on selecting the image from the shopping cart..But here i am getting image of first item only no matter i have clicked another..it is always showing first image of the list...
Here is my code for ProductAdapter.java
public class ProductAdapter extends BaseAdapter {
private List<Product> mProductList;
private LayoutInflater mInflater;
private boolean mShowQuantity;
public ProductAdapter(List<Product> list, LayoutInflater inflater, boolean showQuantity) {
mProductList = list;
mInflater = inflater;
mShowQuantity = showQuantity;
}
#Override
public int getCount() {
return mProductList.size();
}
#Override
public Object getItem(int position) {
return mProductList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewItem item;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item, null);
item = new ViewItem();
item.productImageView = (ImageView) convertView
.findViewById(R.id.ImageViewItem);
item.productTitle = (TextView) convertView
.findViewById(R.id.TextViewItem);
item.productQuantity = (TextView) convertView
.findViewById(R.id.textViewQuantity);
convertView.setTag(item);
} else {
item = (ViewItem) convertView.getTag();
}
Product curProduct = mProductList.get(position);
item.productImageView.setImageDrawable(curProduct.productImage);
item.productTitle.setText(curProduct.title);
// Show the quantity in the cart or not
if (mShowQuantity) {
item.productQuantity.setText("Quantity: "
+ ShoppingCartHelper.getProductQuantity(curProduct));
} else {
// Hid the view
item.productQuantity.setVisibility(View.GONE);
}
return convertView;
}
private class ViewItem {
ImageView productImageView;
TextView productTitle;
TextView productQuantity;
}}
And Here is my shoppingcart file
public class ShoppingCartActivity extends Activity {
private List<Product> mCartList;
private ProductAdapter mProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shoppingcart);
mCartList = ShoppingCartHelper.getCartList();
// Make sure to clear the selections
for (int i = 0; i < mCartList.size(); i++) {
mCartList.get(i).selected = false;
}
// Create the list
final ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
mProductAdapter = new ProductAdapter(mCartList, getLayoutInflater(),
true);
listViewCatalog.setAdapter(mProductAdapter);
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),
ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
startActivity(productDetailsIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
// Refresh the data
if (mProductAdapter != null) {
mProductAdapter.notifyDataSetChanged();
}
double subTotal = 0;
for (Product p : mCartList) {
int quantity = ShoppingCartHelper.getProductQuantity(p);
subTotal += p.price * quantity;
}
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewSubtotal);
productPriceTextView.setText("Subtotal: $" + subTotal);
}
}
ProductActivity.java
public class CatalogActivity extends Activity {
private List<Product> mProductList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.catalog);
// Obtain a reference to the product catalog
mProductList = ShoppingCartHelper.getCatalog(getResources());
// Create the list
ListView listViewCatalog = (ListView) findViewById(R.id.ListViewCatalog);
listViewCatalog.setAdapter(new ProductAdapter(mProductList, getLayoutInflater(), false));
listViewCatalog.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent productDetailsIntent = new Intent(getBaseContext(),ProductDetailsActivity.class);
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX, position);
startActivity(productDetailsIntent);
}
});
Button viewShoppingCart = (Button) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
startActivity(viewShoppingCartIntent);
}
});
}
}
Code for ProductDetailsActivity.java
public class ProductDetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.productdetails);
List<Product> catalog = ShoppingCartHelper.getCatalog(getResources());
int productIndex = getIntent().getExtras().getInt(
ShoppingCartHelper.PRODUCT_INDEX);
final Product selectedProduct = catalog.get(productIndex);
// Set the proper image and text
ImageView productImageView = (ImageView) findViewById(R.id.ImageViewProduct);
productImageView.setImageDrawable(selectedProduct.productImage);
TextView productTitleTextView = (TextView) findViewById(R.id.TextViewProductTitle);
productTitleTextView.setText(selectedProduct.title);
TextView productDetailsTextView = (TextView) findViewById(R.id.TextViewProductDetails);
productDetailsTextView.setText(selectedProduct.description);
TextView productPriceTextView = (TextView) findViewById(R.id.TextViewProductPrice);
productPriceTextView.setText("$" + selectedProduct.price);
// Update the current quantity in the cart
TextView textViewCurrentQuantity = (TextView) findViewById(R.id.textViewCurrentlyInCart);
textViewCurrentQuantity.setText("Currently in Cart: "
+ ShoppingCartHelper.getProductQuantity(selectedProduct));
// Save a reference to the quantity edit text
final EditText editTextQuantity = (EditText) findViewById(R.id.editTextQuantity);
Button addToCartButton = (Button) findViewById(R.id.ButtonAddToCart);
addToCartButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Check to see that a valid quantity was entered
int quantity = 0;
try {
quantity = Integer.parseInt(editTextQuantity.getText()
.toString());
if (quantity < 0) {
Toast.makeText(getBaseContext(),
"Please enter a quantity of 0 or higher",
Toast.LENGTH_SHORT).show();
return;
}
} catch (Exception e) {
Toast.makeText(getBaseContext(),
"Please enter a numeric quantity",
Toast.LENGTH_SHORT).show();
return;
}
// If we make it here, a valid quantity was entered
ShoppingCartHelper.setQuantity(selectedProduct, quantity);
// Close the activity
finish();
}
});
}
Plz guys Any help will be highly appreciated.
Thanx in advance..
The int position in onItemClick gives the position of the clicked item in the array/list you gave to the adapter.
You can also do getItemAtPosition(); on your listview, if you don't have an easy handle on your original list.
add this code to your Project :
mProductList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,
View v, int position, long id)
{
int h = parent.getPositionForView(v);
Toast.makeText(getBaseContext(),
"pic" + (position + 1) + " selected" + h,
Toast.LENGTH_SHORT).show();
}
});
Just geussig that you have a problematic code where you are reading the index value. Following is the sample code for writing and reading int extra:
To put int value:
productDetailsIntent.putExtra(ShoppingCartHelper.PRODUCT_INDEX,
position);
Following code should be used to read this value in another Activity
int index = getIntent().getExtras().getInt(ShoppingCartHelper.PRODUCT_INDEX);
Hope it helps...