I have a listview. Each row of a listview contains two texts (name and aaddress), one button and one radio button. I am using CustomAdapter for that. Now I have a condition; if a text1(name) is equal to "Pramod", then I have to delete the radio button from entire rows.
What is happening exactly? The radio button of only that row is deleting.
I have to delete the radio button of all rows. How do I fix that?
Here is my code of customAdapter class:
public class CustomAdapter extends ArrayAdapter<Item> {
private final Context context;
// private boolean userSelected = false;
public static RadioButton mCurrentlyCheckedRB;
private final ArrayList<Item> itemList;
int selected_itemindex=-1;
static String abc="";
public CustomAdapter(Context context, ArrayList<Item> itemList) {
super(context, R.layout.row_item, itemList);
this.context = context;
this.itemList = itemList;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
final View rowView = inflater.inflate(R.layout.row_item, parent, false);
// 3. Get the two text view from the rowView
Button btn = (Button) rowView.findViewById(R.id.button1);
TextView tv1 = (TextView) rowView.findViewById(R.id.textView1);
final TextView tv2 = (TextView) rowView.findViewById(R.id.textView2);
final RadioButton radio = (RadioButton) rowView.findViewById(R.id.radioButton1);
// 4. Set the text for textView
tv1.setText(itemList.get(position).getName());
tv2.setText(itemList.get(position).getAddress());
// This is the code I am using to delete the radio button from the entire row
if (itemList.get(position).getName().toString().equals("Pramod")) {
radio.setVisibility(View.INVISIBLE);
}
if (itemList.get(position).isSelected()) {
radio.setChecked(true);
rowView.setBackgroundColor(Color.CYAN);
}
else {
rowView.setBackgroundColor(Color.WHITE);
radio.setChecked(false);
}
// The radio button I am using to select a particular row one at a time.
radio.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (itemList.get(position).isSelected()) {
}
else
{
int selected_previousval = -1;
for (int i=0; i<itemList.size(); i++) {
if (itemList.get(i).isSelected()) {
selected_previousval = i;
break;
}
}
String name2=itemList.get(position).getName();
String add2=itemList.get(position).getAddress();
if (selected_previousval==-1) {
itemList.remove(position);
itemList.add(position,new Item(name2, add2, true));
rowView.setBackgroundColor(Color.CYAN);
Toast.makeText(context, "selected a 3 row",2000).show();
radio.setChecked(true);
}
else {
itemList.remove(position);
itemList.add(position, new Item(name2, add2, true));
name2 = itemList.get(selected_previousval).getName();
add2 = itemList.get(selected_previousval).getAddress();
itemList.remove(selected_previousval);
itemList.add(selected_previousval, new Item(name2, add2, false));
MainActivity.lv.setAdapter(new CustomAdapter(context, itemList));
}
}
}
});
return rowView;
}
}
And this is my Arraylist class:
public class Item {
private String Name;
private String Address;
public boolean selected;
public boolean isSelected() {
return this.selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Item(String Name, String Address,boolean selected) {
super();
this.Name = Name;
this.Address = Address;
this.selected=selected;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
UPDATE
Question: I want to remove the radiobutton from every row of listview if text=pramod.
Answer:
MainActivity class
ArrayList<Item> items;
CustomAdapter adapter;
items = new ArrayList<Item>();
ArrayList<String> temparray;
items.add(new Item("Pramod", "Ballia", false, 0));
items.add(new Item("Pankaj", "Mau", false, 1));
items.add(new Item("Pradeep", "Ranchi", false, 1));
items.add(new Item("Jitendra", "Varansi", false, 1));
items.add(new Item("Amresh", "Sonbhadra", false, 1));
items.add(new Item("Anil", "Sarnath", false, 1));
temparray = new ArrayList<String>();
for(int i=0; i<items.size(); i++)
{
temparray.add(items.get(i).getName());
}
if (temparray.contains("Pramod"))
{
Log.d("temparray", "contains Pramod");
Global.show=0;
}
else
{
Log.d("temparray", "not contain");
Global.show=1;
}
lv = (ListView)dp.findViewById(R.id.listView1);
Spinner sp = (Spinner) dp.findViewById(R.id.spinner1);
adapter = new CustomAdapter(this, items);
lv.setAdapter(adapter);
customAdapter.class
if (Global.show == 0)
{
radio.setVisibility(View.INVISIBLE);
}
else
{
radio.setVisibility(View.VISIBLE);
if (itemList.get(position).isSelected()) {
radio.setChecked(true);
rowView.setBackgroundColor(Color.CYAN);
}
else {
rowView.setBackgroundColor(Color.WHITE);
radio.setChecked(false);
}
}
Global.class
public static class Global {
Public static int show;
}
Related
I'm developing an android app which has a custom listview with a checkbox. I want to pass all the checked items from one activity to another. how should I pass them? and where should I manage the checkbox (to get all the checked items) in the custom adapter or the activity?
Note: I retrieve all the data from my server using json response.
Here's my Model :
public class Groups {
public String name;
public boolean selected= false;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Groups() {
}
}
My Adapter:
public class AdapterMainActivity extends BaseAdapter{
Activity activity;
private LayoutInflater inflater;
List<Groups> groupsList;
public AdapterMainActivity(Activity activity, List<Groups> groupses) {
this.activity = activity;
this.groupsList = groupses;
}
#Override
public int getCount() {
return groupsList.size();
}
#Override
public Object getItem(int position) {
return groupsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_list, null);
TextView name = (TextView) convertView.findViewById(R.id.textViewName);
final CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
final Groups groups = groupsList.get(position);
name.setText(groupsList.get(position).getName());
checkBox.setChecked(groups.selected);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
groups.selected = isChecked;
MainActivity.getInstance().updateArrayList(groupsList);
}
});
}
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
ListView listViewGroups;
Button buttonSentToActivity;
List<Groups> groupsList;
List<Groups> resultGroupList;
ArrayList<Boolean> areChecked;
List<String> finalArray;
private AdapterMainActivity adapterMainActivity;
static MainActivity yourActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
yourActivity = this;
groupsList= new ArrayList<Groups>();
resultGroupList= new ArrayList<Groups>();
ReadGroup(37);
adapterMainActivity = new AdapterMainActivity(this, groupsList);
listViewGroups = (ListView) findViewById(R.id.listViewGroups);
listViewGroups.setAdapter(adapterMainActivity);
buttonSentToActivity = (Button) findViewById(R.id.buttonSendTo2Activity);
buttonSentToActivity.setOnClickListener(buttonSentToActivityListener);
Log.e("Group list size ", String.valueOf(groupsList.size()));
finalArray = new ArrayList<>();
for (int i = 0; i < resultGroupList.size(); i++) {
if (resultGroupList.get(i).selected) {
finalArray.add(resultGroupList.get(i).getName());
Log.e("final array size", String.valueOf(finalArray.size()));
}
}
}
public void ReadGroup(long cid) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
JSONArray readArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < readArray.length(); i++) {
Log.e("i is: ", String.valueOf(i));
JSONObject jssonRow = readArray.getJSONObject(i);
String groupName = jssonRow.getString("name");
Groups groups = new Groups();
groups.setName(groupName);
Log.e("NAME is: ", groupName);
groupsList.add(groups);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapterMainActivity.notifyDataSetChanged();
}
};
Log.e("Client id is: ", String.valueOf(cid));
ReadGroupRequesr readGroupRequest = new ReadGroupRequesr(cid, responseListener);
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(readGroupRequest);
Log.e("out of the loop", "");
}
public static MainActivity getInstance() {
return yourActivity;
}
public void updateArrayList(List<Groups> arrayList) {
this.resultGroupList = arrayList;
}
View.OnClickListener buttonSentToActivityListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
//Bundle b= new Bundle();
//b.putStringArrayList("arrayList", (ArrayList<String>) finalArray);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putStringArrayListExtra("arrayList", (ArrayList<String>) finalArray);
//intent.putExtras(b);
Log.e("final array size", String.valueOf(finalArray.size()));
startActivity(intent);
}
};
}
At the very first, manage your checkboxes :
In your activity class add a boolean array or arraylist having size same as your list array size and initialize it with all value as false initially :
String[] titlesArray;
ArrayList<Boolean> arrChecked;
// initialize arrChecked boolean array and add checkbox value as false initially for each item of listview
arrChecked = new ArrayList<Boolean>();
for (int i = 0; i < titles.size(); i++) {
arrChecked.add(false);
}
Now replace your adapter class with this :
class VivzAdapter extends ArrayAdapter<String> implements OnCheckedChangeListener {
Context context;
int[] images;
String[] titlesArray, descrptionArray;
List<Integer> positions = new ArrayList<Integer>();
ArrayList<Boolean> arrChecked;
VivzAdapter(Context context, String[] titles, int[] images, String[] description, ArrayList<Boolean> arrChecked) {
super(context, R.layout.single_row, R.id.textView1, titles);
this.context = context;
this.images = images;
this.titlesArray = titles;
this.descrptionArray = description;
this.arrChecked = arrChecked;
}
class MyViewHolder {
ImageView myImage;
TextView myTitle;
TextView myDescription;
CheckBox box;
MyViewHolder(View v) {
myImage = (ImageView) v.findViewById(R.id.imageView1);
myTitle = (TextView) v.findViewById(R.id.textView1);
myDescription = (TextView) v.findViewById(R.id.textView2);
box = (CheckBox) v.findViewById(R.id.checkBox1);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
MyViewHolder holder = null;
if (row == null) {
// 1.ºtime
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//row contem RelativeLayout(root) em single_row.xml
row = inflater.inflate(R.layout.single_row, parent, false);
holder = new MyViewHolder(row);
row.setTag(holder);
//Log.d("VIVZ", "Creating a new Row");
} else {
//reciclamos aqui, qeremos usar antigo objecto holder
holder = (MyViewHolder) row.getTag();
//Log.d("VIVZ", "Recycling stuff");
}
holder.myImage.setImageResource(images[position]);
holder.myTitle.setText(titlesArray[position]);
holder.myDescription.setText(descrptionArray[position]);
//set position as id
holder.box.setId(position);
//set onClickListener of checkbox rather than onCheckedChangeListener
holder.box.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int id = v.getId();
if (arrChecked.get(id)) {
//if checked, make it unchecked
arrChecked.set(id, false);
} else {
//if unchecked, make it checked
arrChecked.set(id, true);
}
}
});
//set the value of each checkbox from arrChecked boolean array
holder.box.setChecked(arrChecked.get(position));
return row;
}
}
After that, implement click listener of send button say btnSend button (I am considering that you are sending your data from one activity to another activity on click of send button) :
btnSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<String> arrTempList = new ArrayList();
for(int i=0; i<titles.size(); i++){
if(arrChecked.get(i) == true){
arrTempList.add(titles[i]);
}
}
// here you can send your arrTempList which is having checked items only
}
});
Here's the solution for this Question:
My adapter:
public class ChooseContactsAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
public ArrayList<Contacts> contactsList;
public CheckBox checkBoxAdapter;
public ChooseContactsAdapter(Activity activity, ArrayList<Contacts> group) {
this.activity = activity;
this.contactsList = group;
}
#Override
public int getCount() {
return contactsList.size();
}
#Override
public Object getItem(int position) {
return contactsList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null) {
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_choose_contacts_sms,
null);
final TextView fNAme = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactFName);
TextView LName = (TextView) convertView.findViewById(R.id.textViewCustomSMSSelectContactLName);
checkBoxAdapter = (CheckBox) convertView.findViewById(R.id.checkBoxSelectContact);
checkBoxAdapter.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
CheckBox cb = (CheckBox) view;
Contacts contacts = (Contacts) cb.getTag();
contacts.setSelected(cb.isChecked());
Toast.makeText(activity.getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
}
});
final Contacts contacts = contactsList.get(position);
fNAme.setText(contacts.getContactFName());
LName.setText(contacts.getContactLName());
checkBoxAdapter.setChecked(contacts.isSelected());
checkBoxAdapter.setTag(contacts);
}
return convertView;
}
}
In my activity I have button to go from 1 activity to the 2 activity:
private View.OnClickListener buttonSubmitGroupListener =new View.OnClickListener() {
#Override
public void onClick(View view) {
List <Integer> contactsIDArray= new ArrayList<Integer>();
List<Contacts> arrayOfContacts= chooseContactsAdapter.contactsList;
for(int i=0; i< arrayOfContacts.size(); i++){
Contacts contacts= arrayOfContacts.get(i);
if(contacts.isSelected()==true){
contactsIDArray.add(contacts.getContactID());
}
}
for (int i = 0; i < contactsIDArray.size(); i++) {
Log.e("Id Array size ", String.valueOf(contactsIDArray.size()));
Log.e("Selected id ", String.valueOf(contactsIDArray.get(i)));
}
intent = new Intent(getApplicationContext(), SendSMSActivity.class);
Bundle b = new Bundle();
b.putIntegerArrayList("checkedContacts", (ArrayList<Integer>) contactsIDArray);
intent.putExtras(b);
startActivity(intent);
}
};
Second Activity add this code:
Bundle b = getIntent().getExtras();
List<Integer> result = new ArrayList<Integer>();
result = b.getIntegerArrayList("checkedContacts");
i have an issue when i try to delete multiple checked items from my listView. If i start deleting from down to up items are removed from my list, but there is a problem when i do it from up to down or if random items are checked. The problem is the checked items are not deleted, but the unchecked items are deleted.
public class MainActivity extends ActionBarActivity {
private EditText etn,etl,etd;
private Button add;
private Button rmv;
private ListView listView;
private ArrayList<Data> list;
private MyCustomAdapter dataAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
listView = (ListView) findViewById(R.id.listView1);
list = new ArrayList<Data>();
add = (Button) findViewById(R.id.btn_add);
etn = (EditText) findViewById(R.id.edit_name);
eta = (EditText) findViewById(R.id.edit_lastname);
etd = (EditText) findViewById(R.id.edit_document);
rmv = (Button) findViewById(R.id.btn_delete);
displayView();
}
public class Data {
long document;
String name;
String lastname;
boolean selected = false;
public Data(long document, String name, String lastname, boolean selected){
this.document=document;
this.name=nom;
this.lastname=lastname;
this.selected = selected;
}
public String getName(){
return name;
}
public String getLastName(){
return lastname;
}
public long getDocument(){
return document;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
public void displayView(){
String name = etn.getText().toString();
String lastname= eta.getText().toString();
long document = Integer.valueOf(etd.getText().toString());
Data edata = new Data(document,name,lastname,false);
list.add(edata);
dataAdapter = new MyCustomAdapter(this,
R.layout.list_info, list);
listView.setAdapter(dataAdapter);
}
public void delete(View view){
deleteListItem();
}
private void deleteListItem(){
if(list.isEmpty()){
Toast.makeText(getApplicationContext(),
"No items to delete.",
Toast.LENGTH_LONG).show();
return;
}
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
dataAdapter.notifyDataSetChanged();
}
private class MyCustomAdapter extends ArrayAdapter<Data> {
private ArrayList<Data> list;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Data> list) {
super(context, textViewResourceId, list);
this.list = new ArrayList<Data>();
this.list.addAll(list);
}
private class ViewHolder {
TextView name;
TextView lname;
TextView doc;
CheckBox ck;
}
#Override
public View getView(int position, View convertView, ViewGroupparent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_info, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.ck = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.lname = (TextViewconvertView.findViewById(R.id.lastname);
holder.doc = (TextView)convertView.findViewById(R.id.document);
convertView.setTag(holder);
holder.ck.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Data edata = (Data) cb.getTag();
Toast.makeText(getApplicationContext(),
"Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show();
edata.setSelected(cb.isChecked());
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
Data aux = list.get(position);
long document = aux.getDocument();
holder.doc.setText("Doc:" + Long.toString(document));
holder.name.setText (" " + "Name:" + aux.getName()+ " ");
holder.lname.setText("Last name:" + aux.getLastName());
holder.ck.setTag(aux);
holder.ck.setChecked(aux.isSelected());
return convertView;
}
}
I think problem resides in this block :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = list.get(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Try like this :
int itemCount = listView.getCount();
for(int i=itemCount - 1 ; i>=0; i--){
Data aux = dataAdapter.getItem(i);
if(aux.isSelected()){
dataAdapter.remove(aux);
}
}
Note : I am not sure, Please try and let me know the result .:)
I have custom list within each row have imageview,textview and radio button .
I select one radio button and i want to get the image of the same row of selected radio button.
I tried many times but no succeeded help me and i am a quite new user of android.
public class rowadapter extends ArrayAdapter<String>
{
private final Activity context;
int layoutResourceId;
private final String[] image_name;
private final Integer[] imageId;
int selectedPosition = -1;
int selectedimg=-1;
SharedPreferences sharedPref;
public rowadapter(Activity context,String[] image_name, Integer[] imageId) {
super(context,R.layout.item_listview, image_name);
this.context = context;
this.image_name = image_name;
this.imageId = imageId;
sharedPref = context.getSharedPreferences("position",Context.MODE_PRIVATE);
}
public View getView(final int position, View row, ViewGroup parent)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
backgroundholder holder = null ;
View rowView=row;
rowView= inflater.inflate(R.layout.item_listview, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.txt);
final ImageView imageView = (ImageView) rowView.findViewById(R.id.img);
txtTitle.setText(image_name[position]);
//holder.lvv=(ListView)rowView.findViewById(R.id.lv);
imageView.setImageResource(imageId[position]);
holder = new backgroundholder();
holder.radiobutton = (RadioButton)rowView.findViewById(R.id.radiobutton);
holder.radiobutton.setChecked(position == selectedPosition);
holder.radiobutton.setTag(position);
int checkedpos=sharedPref.getInt("position",-1);
if(checkedpos==position)
{
holder.radiobutton.setChecked(true);
}
holder.radiobutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
selectedPosition = (Integer)view.getTag();
RadioButton radio = (RadioButton)view;
if(radio.isChecked())
{
Editor editor=sharedPref.edit();
editor.putInt("position", selectedPosition);
editor.commit();
}
Intent i=new Intent(getContext(), Preferences.class);
context.startActivity(i);
context.finish();
notifyDataSetInvalidated();
}
});
return rowView;
}
static class backgroundholder
{
RadioButton radiobutton;
}
}
//itemclass
public class Item {
String txt;
Integer drawable;
boolean checked;
public Item(String txt,Integer drawable)
{
this.txt=txt;
this.drawable=drawable;
}
public String gettxt()
{
return txt;
}
public Integer getInteger()
{
return drawable;
}
public boolean ischecked()
{
return checked;
}
public void setchecked(boolean checked)
{
this.checked=checked;
}
}
//mainactivity
public class MainActivity extends Activity {
ListView list;
String[] backgrounds = {
"Metallic",
"Wood",
"Sea",
"Garden",
"Tiger",
} ;
Integer[] imageId = {
R.drawable.metallic,
R.drawable.wood,
R.drawable.sea,
R.drawable.garden,
R.drawable.tiger,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.background);
rowadapter adapter = new rowadapter(MainActivity.this, backgrounds, imageId);
list=(ListView)findViewById(R.id.lv);
list.setAdapter(adapter);
Button cancel=(Button)findViewById(R.id.button1);
cancel.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent go=new Intent(MainActivity.this,Preferences.class);
startActivity(go);
}
});
}
}
I have created a custom lisview with images and text by using an array adapter. I would like to highlight one of the row manually, but I cannot seem to do this. I have tried using setItemChecked and setSelection(1);. I have made sure to disable touch events by calling listView.setEnabled(false);, as I read that manual selection might not work if touch events are enabled. Any insight into this matter would be greatly appreciated. I have included my source code below.
Main Activity
public class MainActivity extends Activity
{
// GUI
int Update_Frequency = 1000;
double ack = 0;
// Sensor Constants
public static String temperature = "--";
public static String humidity = "--";
public static String lpg = "--";
public static String alcohol = "--";
// Layout
ListView listView;
ItemAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize Interface
Model.LoadModel();
listView = (ListView) findViewById(R.id.listView);
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++)
{ids[i] = Integer.toString(i+1);}
this.adapter = new ItemAdapter(this,R.layout.row, ids);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setEnabled(false);
listView.setItemChecked(1, true);
listView.setSelection(1);
Model.LoadModel();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
GUI_Management();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_connect:
break;
case R.id.action_disconnect:
break;
case R.id.action_settings:
break;
case R.id.action_about:
break;
case R.id.action_exit:
break;
default:
break;
}
return true;
}
private void GUI_Management()
{
new Thread()
{
public void run()
{
//Replace with a changeable variable
while (true)
{
try
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Model.LoadModel();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
Thread.sleep(Update_Frequency);
}
catch (InterruptedException e)
{
}
}
}
}.start();
}
}
Array Adapter
public class Model extends MainActivity
{
public static ArrayList<Item> Items;
public static void LoadModel()
{
Items = new ArrayList<Item>();
Items.add(new Item(1, "temperature_icon.png", "Temperature/Humidity " + temperature + "°F / " + humidity + "%"));
Items.add(new Item(2, "gas_icon.png", "LPG " + lpg +" ppm"));
Items.add(new Item(3, "alcohol_icon.png", "Alcohol " + alcohol + " ppm"));
}
public static Item GetbyId(int id)
{
for(Item item : Items)
{
if (item.Id == id)
{
return item;
}
}
return null;
}
}
class Item
{
public int Id;
public String IconFile;
public String Name;
public Item(int id, String iconFile, String name)
{
Id = id;
IconFile = iconFile;
Name = name;
}
}
class ItemAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] Ids;
private final int rowResourceId;
public ItemAdapter(Context context, int textViewResourceId, String[] objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.Ids = objects;
this.rowResourceId = textViewResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
TextView textView = (TextView) rowView.findViewById(R.id.textView);
int id = Integer.parseInt(Ids[position]);
String imageFile = Model.GetbyId(id).IconFile;
textView.setText(Model.GetbyId(id).Name);
// get input stream
InputStream ims = null;
try {
ims = context.getAssets().open(imageFile);
} catch (IOException e) {
e.printStackTrace();
}
// load image as Drawable
Drawable d = Drawable.createFromStream(ims, null);
// set image to ImageView
imageView.setImageDrawable(d);
return rowView;
}
}
put setonclick listener in rootview object which are inflate by you in getview method this will solve your issue and on click event you can change the background of rootview and many more you can do with it.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(rowResourceId, parent, false);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imageView);
TextView textView = (TextView) rowView.findViewById(R.id.textView);
int id = Integer.parseInt(Ids[position]);
String imageFile = Model.GetbyId(id).IconFile;
textView.setText(Model.GetbyId(id).Name);
if (position == selectedItem)
{
rootView /*or you can use any viewgroup*/
.setBackgroundResource(R.drawable.background_dark_blue);
}
else
{
rootView
.setBackgroundResource(R.drawable.border02);
}
return rowView;
}
private int selectedItem;
public void setSelectedItem(int position) {
selectedItem = position;
}
i know this is not good solutionbut might this help you out you can use setSelectedItem method to highlight row
and please use static placeholder class for efficiency and use position field in static placeholder class to get position of selected row
Hai i'm trying to develop an app where by i can send sms and email to a particular group of people..
I have a listview showing the contacts which are in my group.Each row is of the form
TextView(Name)TextView(phone) Checkbox(sms)
TextView(email id) Checkbox(mail)
I have used custom adapter to display the contact details to the listview.ihave set the onitemclick listener to find the position of the row..
I have to send sms and email to those contacts for which checkboxes have been set as true.how can i find the state of each of the checkboxes.
Please help me..lotz of thanx in advance..
I hav added below the custom adapetr i hv created..
public class ContactInfoAdapter extends ArrayAdapter{
private ArrayList<Boolean> mChecked_sms,mChecked_email;
Context context;
int layoutResourceId;
ContactInfo data[] = null;
public ContactInfoAdapter(Context context, int layoutResourceId, ContactInfo[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
mChecked_sms = new ArrayList<Boolean>();
mChecked_email = new ArrayList<Boolean>();
for (int i = 0; i < this.getCount(); i++) {
mChecked_sms.add(i, false);
mChecked_email.add(i,false);
}
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ContactHolder holder;
View row = convertView;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ContactHolder();
holder.txtName = (TextView)row.findViewById(R.id.textViewName);
holder.txtPhone = (TextView) row.findViewById(R.id.textViewPhone);
holder.txtEmail = (TextView) row.findViewById(R.id.textViewEmail);
holder.cb_sms_state = (CheckBox) row.findViewById(R.id.checkBox1);
holder.cb_email_state = (CheckBox) row.findViewById(R.id.checkBox2);
row.setTag(holder);
}
else
{
holder = (ContactHolder)row.getTag();
}
ContactInfo contact = data[position];
holder.txtName.setText(contact.name);
holder.cb_sms_state.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (holder.cb_sms_state.isChecked()) {
mChecked_sms.set(position, true);
Toast.makeText(getContext(), "checked", 2).show();
} else {
mChecked_sms.set(position, false);
}
}
});
holder.cb_sms_state.setChecked(mChecked_sms.get(position));
holder.cb_email_state.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (holder.cb_email_state.isChecked()) {
mChecked_email.set(position, true);
Toast.makeText(getContext(), "checked", 2).show();
} else {
mChecked_email.set(position, false);
}
}
});
holder.cb_email_state.setChecked(mChecked_email.get(position));
holder.txtPhone.setText(contact.number);
holder.txtEmail.setText(contact.email);
return row;
}
static class ContactHolder
{
TextView txtName;
TextView txtPhone;
TextView txtEmail;
CheckBox cb_sms_state;
CheckBox cb_email_state;
}
}
The ContactInfo class is :
public class ContactInfo {
public String name;
public String number;
public String email;
public boolean sms_state;
public boolean email_state;
public ContactInfo(){
super();
}
public ContactInfo(String name,String number,String email,boolean sms_state,boolean email_state) {
super();
this.name = name;
this.number = number;
this.email = email;
this.sms_state = sms_state;
this.email_state = email_state;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setNUmber(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
public void setEmail(String email) {
this.email = email;
}
public String getEmail() {
return email;
}
public void setSms_state(Boolean sms_state)
{
this.sms_state = sms_state;
}
public Boolean getSms_state(){
return sms_state;
}
public void setEmail_state(Boolean email_state)
{
this.email_state = email_state;
}
public Boolean getEmail_state(){
return email_state;
}
Inside the getView() method, you have to implement a OnCheckedChangeListener for the CheckBox.
Here is a listener code, say for example:
ChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
See the doc.
I think you need :
checkbox.isChecked()
Here's a simple sample:
mContactListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
CheckBox chkContact = (CheckBox) view.findViewById(R.id.listrow_contact_chkContact);
if (chkContact.isChecked()) {
...
}
});
I've had this problem with my app Hasta La Vista I've create a with custom listview with checked items and I needed to get checked items this was the solution:
ListView lv = getListView(); //ver listview
if(lv != null){
final SparseBooleanArray checkedItems = lv.getCheckedItemPositions(); //get checked items
if (checkedItems == null) {
return;
}
final int checkedItemsCount = checkedItems.size();
for (int i = 0; i < checkedItemsCount; ++i) {
// This tells us the item position we are looking at
final int position = checkedItems.keyAt(i);
// This tells us the item status at the above position
final boolean isChecked = checkedItems.valueAt(i);
if(isChecked){
//get item from list and do something
lv.getAdapter().getItem(position);
}
}
}
As ListView views are recycled, you can not rely on listening on particular instance, you will have to store "checked" state in your data model. You will also need custom list adapter, where you create and populate individual entries. Following shall be done:
- in overriden getView(), either create new view ( in case no convertView was supplied ) or inflate new one
- populate viewv fields from you data model
- remove old onclick listener, and set new one ( can be anonymous inner class ) modifying your data model
PS: recycling views is important if your list is big