I read many more realted to this problem but not getting more idea. After this, i am trying to post, here in this picture I have 3 items on list, I have 2 item click. So I want to delete these two checked item. But i am the newbie for android, So could not get more idea behind this.
Code
public class CountryList extends Activity implements OnClickListener,
OnItemClickListener {
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempCountry.length;
}
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.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.country);
holder.checkBox = (CheckedTextView) convertView
.findViewById(android.R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtcnt.setText(country[position]);
return convertView;
}
static class ViewHolder {
TextView txtcnt;
CheckBox checkBox;
}}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
lv = (ListView) findViewById(R.id.list);
btn_delete = (Button) findViewById(R.id.delete);
btn_delete.setOnClickListener(this);
checkbox = (CheckBox) findViewById(R.id.checkbox);
txtname= (TextView) findViewById(R.id.body);
String name= pref.getString("name", "");
country= name.split(",");
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder .setMessage("Are you Sure want to delete checked country ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// how to remove country
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Delete Country");
alert.show();
case R.id.checkbox:
//What is the procedue in this section
default:
break;
}
}
public void onItemClick(AdapterView<?> pareant, View view, int position,
long id) {
try {
// I have trying this but could not proper output or only errors
SparseBooleanArray sp = lv.getCheckedItemPositions();
/*String str = "";
for (int i = 0; i < sp.size(); i++) {
str += country[sp.keyAt(i)] + ",";
}*/
} catch (Exception e) {
e.printStackTrace();
}}}
This is the only three country, actually, I have more then hundreds countries.
Delete items from tempCountry and then call adapter.notifyDataSetChanged().
Have a button on list and let it onclick feature in xml
like to get postion first
public void OnClickButton(View V){
final int postion = listView.getPositionForView(V);
System.out.println("postion selected is : "+postion);
Delete(postion);
}
public void Delete(int position){
if (adapter.getCount() > 0) {
//Log.d("largest no is",""+largestitemno);
//deleting the latest added by subtracting one 1
comment = (GenrricStoring) adapter.getItem(position);
//Log.d("Deleting item is: ",""+comment);
dbconnection.deleteComment(comment);
List<GenrricStoring> values = dbconnection.getAllComments();
//updating the content on the screen
this.adapter = new UserItemAdapter(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
else
{
int duration = Toast.LENGTH_SHORT;
//for showing nothing is left in the list
Toast toast = Toast.makeText(getApplicationContext(),"Db is empty", duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
Related
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.
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);
}
}
});
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();
}
I have a list view with multi columns... Want to change the background color of a row item that is selected or clicked. Have referred to various articles on stackoverflow but they dont seem to help...What i ve done in OnItemClick is .setBackgroundColor. Cannot use the selector as would want to remember the color change in the sense the row that I have changed color for, when the application relaunches should remember the change...I put the flag value in database and can set the color in getView but how to do it for first time? Here is the code.....
public class AdminMultiColumn extends Activity
{
private ArrayList<HashMap<String,String>> list;
ArrayList<String> al;
AlertDialog.Builder alertDialogBuilder;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_checkoutlist);
lview = (ListView)findViewById(R.id.admin_list);
populateList();
Admin_checkoutlist adapter = new Admin_checkoutlist(this,list);
lview.setAdapter(adapter);
}
private void populateList() {
list = new ArrayList<HashMap<String,String>>();
al = new ArrayList<String>();
testday = c.get(Calendar.DAY_OF_MONTH);
testmonth = c.get(Calendar.MONTH)+1;
testyear = c.get(Calendar.YEAR);
dateget = testday+"-"+testmonth+"-"+testyear;
mdb.open();
va.open();
Cursor c1 = va.getNameTimeinTimeout(dateget);
DatabaseUtils.dumpCursor(c1);
if(c1.moveToFirst())
{
do{
idfromdb = c1.getString(0);
al.add(idfromdb);
namefromdb = c1.getString(1);
al.add(namefromdb);
timefromdb = c1.getString(2);
al.add(timefromdb);
timeoutfromdb = c1.getString(3);
al.add(timeoutfromdb);
}while(c1.moveToNext());
}
c1.close();
va.close();
mdb.close();
Log.d("pavan","data retrived "+namefromdb+" "+timeoutfromdb+" "+timefromdb+" "+idfromdb);
for(int i = 0;i<al.size();i=i+4)
{
temp = new HashMap<String,String>();
temp.put(FIRST_COLUMN, al.get(i));
temp.put(SECOND_COLUMN, al.get(i+1));
temp.put(THIRD_COLUMN, al.get(i+2));
temp.put(FOURTH_COLUMN, al.get(i+3));
Log.d("pavan","test here for admin");
list.add(temp);
}
}
//adapter class goes here////////////
public class Admin_checkoutlist extends BaseAdapter implements OnItemClickListener
{
public ArrayList<HashMap<String,String>> list;
Activity activity;
public Admin_checkoutlist(Activity activity, ArrayList<HashMap<String,String>> list)
{
super();
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int pos) {
// TODO Auto-generated method stub
return list.get(pos);
}
#Override
public long getItemId(int pos) {
// TODO Auto-generated method stub
return 0;
}
public class ViewHolder
{
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
TextView txtFOURTH;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.temp, null);
holder = new ViewHolder();
holder.txtFirst = (TextView)convertView.findViewById(R.id.uid);
holder.txtSecond = (TextView)convertView.findViewById(R.id.nametext);
holder.txtThird = (TextView)convertView.findViewById(R.id.checkintext);
holder.txtFOURTH = (TextView)convertView.findViewById(R.id.checkouttext);
convertView.setTag(holder);
lview.setOnItemClickListener(this);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> map = list.get(position);
holder.txtFirst.setText(map.get(FIRST_COLUMN));
holder.txtSecond.setText(map.get(SECOND_COLUMN));
holder.txtThird.setText(map.get(THIRD_COLUMN));
holder.txtFOURTH.setText(map.get(FOURTH_COLUMN));
return convertView;
}//getview ends here.
#Override
public void onItemClick(final AdapterView<?> parent, final View view, int pos,
long id) {
// TODO Auto-generated method stub
Object listItem = parent.getFirstVisiblePosition()+pos+1;
//lview.getChildAt(pos).setBackgroundColor(R.color.blue);
view.setBackgroundColor(pos);
idtosend = listItem.toString();
Log.d("pavan","id is"+idtosend);
/////alert displaing block starts here////////////////////////////////
alertDialogBuilder = new AlertDialog.Builder(AdminMultiColumn.this);
alertDialogBuilder.setTitle("Alert");
alertDialogBuilder
.setMessage("Check out now")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
Toast.makeText(getApplicationContext(), "Checkout successfull", Toast.LENGTH_LONG).show();
testhour = c.get(Calendar.HOUR_OF_DAY);
testmin = c.get(Calendar.MINUTE);
testsec = c.get(Calendar.SECOND);
timings = testhour+":"+testmin+":"+testsec;
mdb.open();
va.open();
va.upDate(idtosend,timings);
Toast.makeText(getApplicationContext(), "update the checkout options "+timings, Toast.LENGTH_SHORT).show();
va.close();
mdb.close();
/*Intent go = new Intent(AdminMultiColumn.this,MultiColumn.class);
startActivity(go);*/
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
///////alert displaing block ends here//////////////////////////////////
}
}
}
What I have done now is within the getView method, taking the convertView and setting the background resource to a color, that too is not working...below is the code...
if(holder.txtFOURTH!=null)
{
convertView.setBackgroundColor(R.drawable.image_border);
}
else
{
Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_SHORT).show();
}
There two points -
pos is not a good option as color
Instead of view.setBackgroundColor(pos); sue
LinearLayout row = (LinearLayout)view.findViewById(R.id.list_row);
if(null!=row){
//<listAdapter>.notifyDataSetChanged();
row.setBackgroundResource(R.drawable.);
}
assuming the your list row has LinearLayout in root having id "list_row", chage this as per your layout.
but there will be problem this as when you click on the second row it also be selected stated and better to call list.notifydatasetchaged there are few more option look over them, may fill your requirement
android-selected-state-listview-example
android-how-do-i-highlight-a-row-in-listview
highlighting-the-selected-item-in-the-listview-in-android
I am trying to deleted checked item in listview in android, but I haven't achive this, why? my code is below. please response . I have try this code as well , which has not get more idea.
How to delete check box items from list
and many more related to delete list item form list view.
public class BookmarksJokes extends Activity implements OnClickListener,
OnItemClickListener {
ListView lv;
static ArrayList<Integer> checks=new ArrayList<Integer>();
static String[] tempTitle = new String[100];
static String[] tempBody = new String[100];
static String[] pos = new String[100];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTitle.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.titleJok);
holder.text2 = (TextView) convertView
.findViewById(R.id.bodyJok);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
holder.text1.setText(tempTitle[position]);
holder.text2.setText(tempBody[position]);
return convertView;
}
class ViewHolder {
TextView text1;
TextView text2;
CheckBox checkBox;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
setUpViews();
for(int b=0;b<tempTitle.length;b++){
checks.add(b,0); //Assign 0 by default in each position of ArrayList
}
String one = pref.getString("title", "");
String two = pref.getString("body", "");
tempTitle = one.split(",");
tempBody = two.split(",");
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
for(int i=0;i<checks.size();i++){
if(checks.get(i)==1){
Log.d(TAG, "i Value >>"+i);
checks.remove(i);
// i--;
Log.d(TAG, "checked Value >>"+checks);
Log.d(TAG, "i Value -- >>"+i);
}
}
((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Delete Jokes");
alert.show();
case R.id.checkbox:
default:
break;
}
}
please update this code with no errors. Or give be best idea for this.
You are removing items from a list while traversing it. At least you must make sure to account for the removed item in the counter variable and the list size (which is why there is an i-- in the original code, but you have commented it out).
I.e. after you deleted the item with index 2, the next in the list is still 2, not 3.
Un-comment the i--, that should fix it.
you want to delete checked item, but not modifying data source of list, please load data source from checks list. as Below:
public class BookmarksJokes extends Activity implements OnClickListener,
OnItemClickListener {
ListView lv;
static ArrayList<Integer> checks=new ArrayList<Integer>();
static ArrayList<String> tempTitle = new String[100];
static ArrayList<String> tempBody = new String[100];
static String[] pos = new String[100];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTitle.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.titleJok);
holder.text2 = (TextView) convertView
.findViewById(R.id.bodyJok);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
holder.text1.setText(tempTitle.get(position));
holder.text2.setText(tempBody.get(position));
return convertView;
}
class ViewHolder {
TextView text1;
TextView text2;
CheckBox checkBox;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
setUpViews();
for(int b=0;b<tempTitle.size();b++){
checks.add(b,0); //Assign 0 by default in each position of ArrayList
}
String one = pref.getString("title", "");
String two = pref.getString("body", "");
String[] tokens = one.split(",");
tempTitle=Arrays.asList(tokens);
tokens= two.split(",");
tempBody =Arrays.asList(tokens);
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
for(int i=0;i<checks.size();i++){
if(checks.get(i)==1){
Log.d(TAG, "i Value >>"+i);
checks.remove(i);
tempTitle.remove(i);
tempBody.remove(i);
// i--;
Log.d(TAG, "checked Value >>"+checks);
Log.d(TAG, "i Value -- >>"+i);
}
}
((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Delete Jokes");
alert.show();
case R.id.checkbox:
default:
break;
}
}