ListView click show/hide all check box - android

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);
}
}
});

Related

ListView lost focus

I am working on an app in android studio.
My app has a listview, whiche has Edittext , textview and checkbox in its row.
my proplem is when I have more than five items in my listvew, the listview lost focus, for example: when I press on checkbox on the 6th item , the textview shows me the name from the first item.
I wish I could explain my proplem very well.
This is my adapter:
public AdapterListView(Context context, int resource, ArrayList<ObjectPeople> arraypeople) {
super(context, resource);
this.mContext = context;
this.arrayPeople = arraypeople;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.mission_name = (TextView) convertView.findViewById(R.id.mission_name);
holder.mission_time = (TextView) convertView.findViewById(R.id.mission_time);
holder.edit_time = (EditText) convertView.findViewById(R.id.edit_time);
holder.mission_image= (ImageView) convertView.findViewById(R.id.mission_image);
holder.cbm = (CheckBox) convertView.findViewById(R.id.checkbo);
convertView.setTag(holder);
holder.cbm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v ) {
CheckBox cb = (CheckBox) v ;
final ObjectPeople person = arrayPeople.get(position);
if(cb.isChecked()) {
arrayPeople.get(position).checkbox= true;
int mis_tm=0;
try{ mis_tm= Integer.parseInt( holder.edit_time.getText().toString());}
catch (Exception e){
cb.setChecked(false);
Toast.makeText(mContext, "يرجى إدخال قيمة معينة", Toast.LENGTH_SHORT).show();}
person.time= mis_tm;
if(mis_tm>0&&mis_tm<1200){
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: "+ person.time );
holder.edit_time.setVisibility(View.GONE);}
else{
cb.setChecked(false);
Toast.makeText(mContext, "يرجى اختيار رقم حقيقي", Toast.LENGTH_SHORT).show();
}
}
else {
arrayPeople.get(position).checkbox= false;
holder.edit_time.setVisibility(View.VISIBLE);
}
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
final ObjectPeople person = arrayPeople.get(position);
holder.mission_name.setText("اسم المهمة: "+person.name);
holder.mission_time.setText( "مدة المهمة: ");
holder.mission_image.setImageResource(arrayPeople.get(position).image);
holder.edit_time.setId(position);
holder.edit_time.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
try {
if (!hasFocus) {
final int position = v.getId();
final EditText Caption = (EditText) v;
arrayPeople.get(position).time = Integer.parseInt(Caption.getText().toString());
}
}catch (Exception e){}
}
});
holder.cbm.setTag(arrayPeople);
return convertView;
}
#Override
public int getCount() {
return arrayPeople.size();
}
static class ViewHolder {
TextView mission_name;
TextView mission_time;
EditText edit_time;
ImageView mission_image;
CheckBox cbm;
}
}
and this select.java which contains the arraylist and list view:
public class select extends AppCompatActivity {
ArrayList<ObjectPeople> arrPeople;
ListView lvPeople;
AdapterListView adapter;
ObjectPeople person;
SharedPreferences settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select);
settings = getApplicationContext().getSharedPreferences("shared", 0);
lvPeople= (ListView) findViewById(R.id.lvPeopl);
arrPeople=new ArrayList<>();
person = new ObjectPeople("حفظ قرآن", 0,false, R.drawable.quran_hifz_r);
arrPeople.add(person);
person = new ObjectPeople("تلاوة قرآن", 0 ,false,R.drawable.img);
arrPeople.add(person);
person = new ObjectPeople("قراءة كتاب", 0 , false,R.drawable.books_r);
arrPeople.add(person);
person = new ObjectPeople("دورات تطوير مهارات", 0 , false,R.drawable.courses_r);
arrPeople.add(person);
person = new ObjectPeople("رياضة", 15 , false,R.drawable.sport_r);
arrPeople.add(person);
final String[] misson_name = new String[1];
Button adf= (Button) findViewById(R.id.add_mission_out_btn);
adf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
View view = LayoutInflater.from(select.this).inflate(R.layout.add_mission_lyt,null);
final EditText add_name = (EditText) view.findViewById(R.id.add_mission_name);
AlertDialog.Builder builder = new AlertDialog.Builder(select.this);
builder.setMessage("add your mission")
.setView(view)
.setPositiveButton("إضافة", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
misson_name[0] = add_name.getText().toString();
arrPeople.add(new ObjectPeople(misson_name[0], 0, true,R.drawable.smile_small_r));
}
})
.setNegativeButton("إلغاء",null)
.setCancelable(false);
AlertDialog alert =builder.create();
alert.show();
}
});
adapter=new AdapterListView(this,R.layout.item_listview,arrPeople);
lvPeople.setAdapter(adapter);
checkButtonClick();
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.btn_save);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences settings = getApplicationContext().getSharedPreferences("shared", 0);
int hours2=settings.getInt("hours",0)*60;
ArrayList<ObjectPeople> selected_missions = new ArrayList<>();
int missoins_time_calc=0;
for (int i = 0; i <arrPeople.size(); i++) {
if(arrPeople.get(i).checkbox==true){
selected_missions.add(arrPeople.get(i));
missoins_time_calc= missoins_time_calc + arrPeople.get(i).time;}
}
if (hours2 == missoins_time_calc){
Gson gson = new Gson();
String jsonText = gson.toJson(selected_missions);
SharedPreferences.Editor editor = settings.edit();
editor.putString("selected_array", jsonText);
editor.commit();
Intent intent = new Intent(select.this, yourprogram.class);
startActivity(intent);
overridePendingTransition(R.anim.fade_in,R.anim.fade_out);
}
else if (hours2 > missoins_time_calc){
Toast.makeText(select.this, "بقي"+(-missoins_time_calc+ hours2)+" دقيقة ", Toast.LENGTH_SHORT).show();}
else if (hours2< missoins_time_calc){
Toast.makeText(select.this,"يوجد "+ (-hours2+missoins_time_calc)+" دقيقة زيادة على الوقت المخصص", Toast.LENGTH_SHORT).show();
}
/* ArrayList<missions> missionsList = dataAdapter.missionsList;
for(int i = 0; i< missionsList.size(); i++){
missions missions = missionsList.get(i);
if(missions.isSelected()){}}*/
}
});
}
}
I think the error is the way your arrayPeople List is being populated, if you say the sixth item gets you the first you can try reversing the order with
Collections.reverse(arrayPeople);
you can place this line of code below your holder.cbm.setOnClickListener on your adapter
Hope it helps.

how to set value list item in adapter class and get value on Button click in android

Adapter Class:
public List<TSPDataModel> employeeData;
private Context mContext;
private LayoutInflater mInflater;
RadioGroup radiogroupbutton;
String[] data = {"Document not clear","Adress is not Visibile","Photo is not pasted","Signature is not Avilable"};
String value;
public TSPListDocumentadapter(Context context, int textViewResourceId,
List<TSPDataModel> objects)
{
this.employeeData = objects;
this.mContext = context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.tspdocumentlistitem, null);
holder.relatvie1=(RelativeLayout)convertView.findViewById(R.id.relatvie1);
holder.txtName = (TextView) convertView.findViewById(R.id.textView1);
holder.accecpt = (ImageView) convertView.findViewById(R.id.imageButton);
holder.reject = (ImageView) convertView.findViewById(R.id.imageButton2);
holder.statustextview = (TextView) convertView.findViewById(R.id.statustextview);
holder.poaedittext=(TextView) convertView.findViewById(R.id.poieditext);
holder.poaedittext=(TextView)convertView.findViewById(R.id.poaedittext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(employeeData.get(position).getName());
holder.poaedittext.setText(employeeData.get(position).getPoa());
holder.accecpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.statustextview.setText("Accepted");
employeeData.get(position).setSelected(true);
employeeData.get(position).getOrderId();
holder.relatvie1.setBackgroundResource(R.color.acceptedcolor);
}
});
holder.reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdilog();
holder.statustextview.setText("Rejected");
employeeData.get(position).setSelected(false);
employeeData.get(position).setReasone(value);
holder.relatvie1.setBackgroundResource(R.color.rejectcolor);
}
});
return convertView;
}
static class ViewHolder {
TextView txtName;
ImageView reject;
ImageView accecpt;
TextView statustextview;
TextView poiedittext;
TextView poaedittext;
RelativeLayout relatvie1;
}
public int getCount() {
return employeeData.size();
}
public TSPDataModel getItem(int position) {
return employeeData.get(position);
}
public long getItemId(int position) {
return 0;
}
public void showdilog() {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.layoutpopup);
radiogroupbutton = (RadioGroup) dialog.findViewById(R.id.radio_gp_day);
ListView listview = (ListView) dialog.findViewById(R.id.radio_slot_list);
Button setbutton = (Button) dialog.findViewById(R.id.setbutton);
List<String> list = new ArrayList<String>();
ArrayAdapter<String> myadpter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_single_choice, data);
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
listview.setAdapter(myadpter);
listview.setItemsCanFocus(false);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
value = data[position];
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
}
});
setbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
This Button click in my actvity class :
#Override
public void onClick(View view) {
if (view.getId() == R.id.button1) {
try {
List<TSPDataModel> empData = adapter.employeeData;
System.out.println("Total Size :" + empData.size());
for (TSPDataModel employeeModel : empData) {
if (employeeModel.isSelected()) {
Toast.makeText(TSPDocumentListActvity.this, employeeModel.getName(), Toast.LENGTH_LONG).show();
} else {
String Reasonse= employeeModel.getresonse() ;
Toast.makeText(TSPDocumentListActvity.this, "false" + employeeModel.getName(), Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
First i Print data in Listview then each list view item there is accept and reject Button is there when we click on accept then no alert will asked only reject button reason will ask which is come on listitem on popup i want to get that selected reason on Button click in actvity but i always get null value please help me where i am doing wrong
change your reject button and showDialog code to
holder.reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdilog(position);
holder.statustextview.setText("Rejected");
holder.relatvie1.setBackgroundResource(R.color.rejectcolor);
}
});
and showDualog to
public void showdilog(int list_position) {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.layoutpopup);
radiogroupbutton = (RadioGroup) dialog.findViewById(R.id.radio_gp_day);
ListView listview = (ListView) dialog.findViewById(R.id.radio_slot_list);
Button setbutton = (Button) dialog.findViewById(R.id.setbutton);
List<String> list = new ArrayList<String>();
ArrayAdapter<String> myadpter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_single_choice, data);
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
listview.setAdapter(myadpter);
listview.setItemsCanFocus(false);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
value = data[position];
employeeData.get(list_position).setSelected(false);
employeeData.get(list_position).setReasone(value);
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
}
});
setbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}

list view repeating values several times and repeating check box selection every after 6th value

I am using a custom list view base adapter. while passing values to the adapter its repeating values. and in viewholder I am using a checkbox, while selecting that checkbox list auto select the every 6th checkbox after that.
here is my adapter full code.
public class CallLogAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater li;
List<CallLogInfo> callData;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
Context context;
static Boolean checkboxstate[];
ArrayList<MultipleSelectedContact> mainDataList;
int i = 0;
public CallLogAdapter(Activity activity, List<CallLogInfo> callData, ArrayList<MultipleSelectedContact> selectedContacts) {
this.activity = activity;
this.callData = callData;
this.mainDataList = selectedContacts;
context = activity;
checkboxstate = new Boolean[callData.size()];
}
// View lookup cache
private static class ViewHolder {
TextView phoneNo, date, addComment, duration;
CheckBox checkBox;
CardView card;
ImageView callTypeImage;
int count;
}
#Override
public int getCount() {
if (callData != null && callData.size() != 0) {
return callData.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return callData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder viewHolder; // view lookup cache stored in tag
if (v == null) {
li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.single_card, parent, false);
viewHolder = new ViewHolder();
viewHolder.card = (CardView) v.findViewById(R.id.card_view);
viewHolder.callTypeImage = (ImageView) v.findViewById(R.id.callTypeImage);
viewHolder.phoneNo = (TextView) v.findViewById(R.id.phoneNoText);
viewHolder.date = (TextView) v.findViewById(R.id.dateText);
viewHolder.duration = (TextView) v.findViewById(R.id.callDurationText);
viewHolder.checkBox = (CheckBox) v.findViewById(R.id.checkBox);
viewHolder.addComment = (TextView) v.findViewById(R.id.addCommentText);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) v.getTag();
}
viewHolder.count = position;
final CallLogInfo Info;
Info = callData.get(position);
switch (Info.callType) {
case "Outgoing":
viewHolder.callTypeImage.setImageResource(R.mipmap.up_arrow);
break;
case "Incoming":
viewHolder.callTypeImage.setImageResource(R.mipmap.down_arrow);
break;
case "Missed":
viewHolder.callTypeImage.setImageResource(R.mipmap.miss_arrow);
break;
}
viewHolder.phoneNo.setText(Info.phoneNo);
viewHolder.date.setText(Info.date);
viewHolder.duration.setText(Info.duration);
viewHolder.addComment.setTag(viewHolder.count);
viewHolder.checkBox.setTag(viewHolder.count);
if (checkboxstate[((int) viewHolder.checkBox.getTag())] == null) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
}
viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
if (((CheckBox) view).isChecked()) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = true;
mainDataList.add(i, new MultipleSelectedContact());
mainDataList.get(i).phoneNoS = Info.phoneNo;
mainDataList.get(i).setIsSelected(viewHolder.checkBox.isSelected());
map.put(((int) viewHolder.checkBox.getTag()), i);
i++;
view.setSelected(true);
} else {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
mainDataList.remove(map.get(((int) viewHolder.checkBox.getTag())));
view.setSelected(false);
}
}
});
viewHolder.addComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_add_comment);
dialog.setTitle("Add Comment Here..");
// set the custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.messageEditText);
Button dialogButton = (Button) dialog.findViewById(R.id.messageAddButton);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String comment = text.getText().toString();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "CallLogDb", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession session = daoMaster.newSession();
CallCommentsDetailDao callCommentDao = session.getCallCommentsDetailDao();
CallCommentsDetail commentInfo = new CallCommentsDetail();
commentInfo.setCommentId(position);
commentInfo.setComments(comment);
callCommentDao.insertOrReplace(commentInfo);
session.clear();
db.close();
dialog.dismiss();
}
});
dialog.show();
}
});
viewHolder.card.setTag(position);
viewHolder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MessageContentActivity.class);
intent.putExtra("callDetails", Info);
context.startActivity(intent);
}
});
return v;
}
}
Here in the code where I am using ((int) viewHolder.checkBox.getTag()) . I tried using position also. but still its not working..
can anyone please help me to find out where I am going wrong
Set your check box state on getView
if (checkboxstate[((int) viewHolder.checkBox.getTag())] == null) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
}
viewholder.checkbox.setChecked(checkboxstate[((int)viewHolder.checkBox.getTag())]);
You can use a SparseBooleanArray to save the states of the checkbox instead of setting it as tag and you are not setting the checkbox state in getView() method like
viewholder.checkbox.setChecked(booleanArray.valueAt(position))
then toggle the state on OnClick() something like
booleanArray.put(position,!booleanArray.valueAt(position));
notifyDataSetChanged();
Also listItemClick won't work properly if the list row contains checkboxes or buttons.Use Recyclerview for better customisation and performance.
Sample Implementation of recyclerview

onclick button is not working in listview

My project contains listView(homelistView) that contains button(btnList).
When I click on button(btnList) it must go to another Activity. I tried a lot but I didn't find a good example.
Please suggest me a good example regarding this.
Below is my code:
Here is my listview contains button. When on click of button it must go to other activity
--------------------------------A--
text text button(btnList) B
--------------------------------C---
text text BUTTON(btnList) D
--------------------------------E--
homempleb.xml
Before i used this code in xml. buttonlist worked fine for me as per below code
<ListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</ListView>
EfficientAdapter.java
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
In your ViewHolder class you need to add `Button btnList.`
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
homempleb.xml
Currently i added scroll index to my listview and changed the code as per below.. Listbutton is not working for me now.. Plz help me u can see code for quick reference in EfficientAdapter.JAVA-----> getview method--->holder.btnList.
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
MainActivity.java
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView listView;
// private IndexableListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
// EfficientAdapter2 objectAdapter1;
int textlength = 0;
private CheckBox checkStat, checkRoutine, checkTat;
private ArrayList<Patient> patientListArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan", " txtScanResult ");
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this,
QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed",
Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE",
Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
// listView = (IndexableListView) findViewById(R.id.homelistView);
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
listView.setFastScrollAlwaysVisible(true);
objectAdapter = new EfficientAdapter(this);
listView.setAdapter(objectAdapter);
Button refreshButton = (Button) findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// objectAdapter1 = new EfficientAdapter2(MainActivity.this);
objectAdapter = new EfficientAdapter(MainActivity.this);// adapter
// with
// new
// data
listView.setAdapter(objectAdapter);
Log.i("notifyDataSetChanged", "data updated");
// objectAdapter1.notifyDataSetChanged();
objectAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.JAVA
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ArrayList<Patient> patientListArray;
private LayoutInflater mInflater;
private Context context;
ViewHolder holder;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
String patientListJson = CountriesList.jsonData;
JSONObject jssson;
try {
jssson = new JSONObject(patientListJson);
patientListJson = jssson.getString("PostPatientDetailResult");
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(patientListJson).getAsJsonArray();
patientListArray = new ArrayList<Patient>();
for (JsonElement obj : Jarray) {
Patient patientList = gson.fromJson(obj, Patient.class);
patientListArray.add(patientList);
Log.i("patientList", patientListJson);
}
}
/**
* sorting the patientListArray data
*/
public void sortMyData() {
// sorting the patientListArray data
Collections.sort(patientListArray, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
Patient p1 = (Patient) o1;
Patient p2 = (Patient) o2;
return p1.getName().compareToIgnoreCase(p2.getName());
}
});
}
public int getCount() {
return patientListArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.name);
holder.text2 = (TextView) convertView.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView.findViewById(R.id.date);
holder.text4 = (TextView) convertView.findViewById(R.id.age);
holder.text5 = (TextView) convertView.findViewById(R.id.gender);
holder.text6 = (TextView) convertView.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView.findViewById(R.id.bedno);
holder.btnList = (Button) convertView.findViewById(R.id.listbutton);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(Util.formatN2H(patientListArray.get(position)
.getName()));
holder.text2.setText(patientListArray.get(position).getMrnNumber());
holder.text3.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text4.setText(Util.formatN2H(patientListArray.get(position)
.getAge()));
holder.text5.setText(Util.formatN2H(patientListArray.get(position)
.getGender()));
holder.text6.setText(Util.formatN2H(patientListArray.get(position)
.getWard()));
holder.text7.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text8.setText(Util.formatN2H(patientListArray.get(position)
.getBed()));
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public int getPositionForSection(int section) {
// sorting the patientListArray data
sortMyData();
// If there is no item for current section, previous section will be
// selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j)
.getName().charAt(0)),
String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j).getName()
.charAt(0)),
String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
The problem is in onInterceptTouchEvent method. You are using IndexableListView from woozzu, and this class overrides onInterceptTouchEvent to return true. This means that IndexableListView always steal touch events from your child's views so it can provide it to IndexScroller. You can change this behavior if instead of returning true you enter this condition:
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mScroller != null && mScroller.contains(ev.getX(), ev.getY()))
return true;
return super.onInterceptTouchEvent(ev);
}
This way only events meant to interact with IndexScroller will be consumed. Other events will be propagated to children's views, and your button will be clickable.
In your Efficient adapter class declare ViewHolder holder outside getView method
and do as MoshErsan said.
Also Change your
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
to
convertView = mInflater.inflate(R.layout.homemplebrowview, parent,false);
in your adapter, just move
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
just before return convertView;
you need to set the listener every time the adapter returns a view.

onclick button in listview in android

My project contains listView(homelistView) that contains button(btnList).
When I click on button(btnList) it must go to another Activity. I tried a lot but I didn't find a good example.
Please suggest me a good example regarding this.
Below is my code:
Here is my listview contains button. When on click of button it must go to other activity
--------------------------------A--
button(btnList) B
--------------------------------C---
BUTTON(btnList) D
--------------------------------E--
homempleb.xml Before i used this code in xml. buttonlist worked fine for me as per Mohith verma sample
<ListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</ListView>
homempleb.xml Currently i added scroll index to my listview and changed the code as per below.. Listbutton is not working for me now..Plz help me
<com.woozzu.android.widget.IndexableListView
android:id="#+id/homelistView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.04"
android:dividerHeight="0dip" >
</com.woozzu.android.widget.IndexableListView>
MainActivity.java
public class MainActivity extends Activity implements
SearchView.OnQueryTextListener, SearchView.OnCloseListener {
private ListView listView;
// private IndexableListView listView;
private SearchView search;
EfficientAdapter objectAdapter;
// EfficientAdapter2 objectAdapter1;
int textlength = 0;
private CheckBox checkStat, checkRoutine, checkTat;
private ArrayList<Patient> patientListArray;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homempleb);
Log.i("scan", " txtScanResult ");
ActionItem nextItem = new ActionItem();
final QuickAction quickAction = new QuickAction(this,
QuickAction.VERTICAL);
quickAction.addActionItem(nextItem);
quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {
#Override
public void onDismiss() {
Toast.makeText(getApplicationContext(), "Dismissed",
Toast.LENGTH_SHORT).show();
}
});
search = (SearchView) findViewById(R.id.searchView1);
search.setIconifiedByDefault(false);
search.setOnQueryTextListener(this);
search.setOnCloseListener(this);
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
quickAction.show(v);
}
});
checkStat = (CheckBox) findViewById(R.id.checkBoxStat);
checkRoutine = (CheckBox) findViewById(R.id.checkBoxRoutine);
checkTat = (CheckBox) findViewById(R.id.checkBoxTat);
checkStat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkStat.setChecked(true);
Toast.makeText(MainActivity.this, "STAT",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkRoutine.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkRoutine.setChecked(true);
Toast.makeText(MainActivity.this, "ROUTINE",
Toast.LENGTH_SHORT).show();
checkStat.setChecked(false);
checkTat.setChecked(false);
}
}
});
checkTat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
checkTat.setChecked(true);
Toast.makeText(MainActivity.this, "TAT Effeciency",
Toast.LENGTH_SHORT).show();
checkRoutine.setChecked(false);
checkStat.setChecked(false);
}
}
});
// listView = (IndexableListView) findViewById(R.id.homelistView);
listView = (ListView) findViewById(R.id.homelistView);
listView.setTextFilterEnabled(true);
listView.setFastScrollEnabled(true);
listView.setFastScrollAlwaysVisible(true);
objectAdapter = new EfficientAdapter(this);
listView.setAdapter(objectAdapter);
Button refreshButton = (Button) findViewById(R.id.refreshButton);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// objectAdapter1 = new EfficientAdapter2(MainActivity.this);
objectAdapter = new EfficientAdapter(MainActivity.this);// adapter
// with
// new
// data
listView.setAdapter(objectAdapter);
Log.i("notifyDataSetChanged", "data updated");
// objectAdapter1.notifyDataSetChanged();
objectAdapter.notifyDataSetChanged();
}
});
}
#Override
public boolean onClose() {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
}
EfficientAdapter.JAVA
public class EfficientAdapter extends BaseAdapter implements SectionIndexer {
private String mSections = "#ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ArrayList<Patient> patientListArray;
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
String patientListJson = CountriesList.jsonData;
JSONObject jssson;
try {
jssson = new JSONObject(patientListJson);
patientListJson = jssson.getString("PostPatientDetailResult");
} catch (JSONException e) {
e.printStackTrace();
}
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray Jarray = parser.parse(patientListJson).getAsJsonArray();
patientListArray = new ArrayList<Patient>();
for (JsonElement obj : Jarray) {
Patient patientList = gson.fromJson(obj, Patient.class);
patientListArray.add(patientList);
Log.i("patientList", patientListJson);
}
}
/**
* sorting the patientListArray data
*/
public void sortMyData() {
// sorting the patientListArray data
Collections.sort(patientListArray, new Comparator<Object>() {
#Override
public int compare(Object o1, Object o2) {
Patient p1 = (Patient) o1;
Patient p2 = (Patient) o2;
return p1.getName().compareToIgnoreCase(p2.getName());
}
});
}
public int getCount() {
return patientListArray.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.homemplebrowview, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.name);
holder.text2 = (TextView) convertView.findViewById(R.id.mrn);
holder.text3 = (TextView) convertView.findViewById(R.id.date);
holder.text4 = (TextView) convertView.findViewById(R.id.age);
holder.text5 = (TextView) convertView.findViewById(R.id.gender);
holder.text6 = (TextView) convertView.findViewById(R.id.wardno);
holder.text7 = (TextView) convertView.findViewById(R.id.roomno);
holder.text8 = (TextView) convertView.findViewById(R.id.bedno);
holder.btnList = (Button) convertView.findViewById(R.id.listbutton);
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "STAT", Toast.LENGTH_SHORT).show();
Intent next = new Intent(context, Home.class);
Log.i("next23", "next");
context.startActivity(next);
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(Util.formatN2H(patientListArray.get(position)
.getName()));
holder.text2.setText(patientListArray.get(position).getMrnNumber());
holder.text3.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text4.setText(Util.formatN2H(patientListArray.get(position)
.getAge()));
holder.text5.setText(Util.formatN2H(patientListArray.get(position)
.getGender()));
holder.text6.setText(Util.formatN2H(patientListArray.get(position)
.getWard()));
holder.text7.setText(Util.formatN2H(patientListArray.get(position)
.getRoom()));
holder.text8.setText(Util.formatN2H(patientListArray.get(position)
.getBed()));
**
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { Intent next=new
Intent(context, Home.class); context.startActivity(next);
} });
**
return convertView;
}
static class ViewHolder {
public Button btnList;
public TextView text8;
public TextView text7;
public TextView text6;
public TextView text5;
public TextView text4;
public TextView text1;
public TextView text2;
public TextView text3;
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public int getPositionForSection(int section) {
// sorting the patientListArray data
sortMyData();
// If there is no item for current section, previous section will be
// selected
for (int i = section; i >= 0; i--) {
for (int j = 0; j < getCount(); j++) {
if (i == 0) {
// For numeric section
for (int k = 0; k <= 9; k++) {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j)
.getName().charAt(0)),
String.valueOf(k)))
return j;
}
} else {
if (StringMatcher.match(
String.valueOf(patientListArray.get(j).getName()
.charAt(0)),
String.valueOf(mSections.charAt(i))))
return j;
}
}
}
return 0;
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
String[] sections = new String[mSections.length()];
for (int i = 0; i < mSections.length(); i++)
sections[i] = String.valueOf(mSections.charAt(i));
return sections;
}
}
First remove btnList, btnScan from your MainActivity class.
In your EfficientAdapter class add object Context Context
Change your contructor:
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
to:
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context=context;
}
In your ViewHolder class you need to add Button btnList.
Then in getview method find its view using holder.btnList
Then use:
holder.btnList.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent next=new Intent(context, SeviceDetails.class);
context.startActivity(next);
}
});
in your getview method before return convertView.
try this..
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_layout_ip_addtional_users, null);
}
//Handle TextView and display string from your list
TextView listItemText2 = (TextView)view.findViewById(R.id.list_item_string_name);
listItemText2.setText(list.get(position));
ImageButton button8 = (ImageButton) view.findViewById(R.id.ip_additional_user_edit);
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, IPAdditionalUsersEdit.class);
context.startActivity(intent);
}
});
return view;
}

Categories

Resources