i have an issue with checked textview - android

i have used checked textview with base adapter to fill listview it's working fine but when i try to scroll CheckedTextView lost the selection.please find the code bellow and help me.
public class AttendancePage extends AppCompatActivity {
List<String> studentNames = new ArrayList<String>();
String[] sNames;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance_page);
databaseHelper = new DatabaseHelper(getApplicationContext());
Cursor res = databaseHelper.getStudentNames();
setTitle("Attendance Sheet");
ListView listView = (ListView) findViewById(R.id.listView);
while (res.moveToNext()) {
studentNames.add(res.getString(0));
}
sNames = new String[studentNames.size()];
sNames = studentNames.toArray(sNames);
Student_Attandence_Addapter customAdapter = new Student_Attandence_Addapter(getApplicationContext(), sNames);
listView.setAdapter(customAdapter);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
My custom Adapter class:
public class Student_Attandence_Adapter extends BaseAdapter {
String[] names;
Context context;
LayoutInflater inflter;
String value;
public Student_Attandence_Adapter(Context context, String[] names) {
this.context = context;
this.names = names;
inflter = (LayoutInflater.from(context));
}
#Override
public int getCount() {
return names.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(names[position]);
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
value = "un-Checked";
simpleCheckedTextView.setCheckMarkDrawable(0);
simpleCheckedTextView.setChecked(false);
} else {
value = "Checked";
simpleCheckedTextView.setCheckMarkDrawable(R.drawable.checked);
simpleCheckedTextView.setChecked(true);
}
}
});
return view;
}
}

Basically what happens is the state of the ChekedTextView will be reset whenever the getView method will be called according to the previous cached state of the list item. So in short you need to store the checked state of an item and when the getView method will be called you need to set it again. For example you need an object containing name and checked state
public class Student {
private String name;
private boolean checked;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
}
and your getView method will be like this,
#Override
public View getView(int position, View view, ViewGroup parent) {
/*
* ListView caches the view so only inflate when there
* is no cached view aka null
*/
if (view == null) {
view = inflter.inflate(R.layout.student_attandence_listview, null);
}
Student aStudent = students[position];
final CheckedTextView simpleCheckedTextView = (CheckedTextView) view.findViewById(R.id.simpleCheckedTextView);
simpleCheckedTextView.setText(aStudent.getName());
simpleCheckedTextView.setCheckMarkDrawable(aStudent.isChecked() ? R.drawable.checked : 0);
simpleCheckedTextView.setChecked(aStudent.isChecked());
simpleCheckedTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (simpleCheckedTextView.isChecked()) {
aStudent.setChecked(false);
notifyDataSetChanged();
} else {
aStudent.setChecked(true);
notifyDataSetChanged();
}
}
});
return view;
}
That's the theme. Modify it as you need.

Related

Apply Listener on some ListView columns

Background:
I have created a ListView with three columns sNo, product and price. First column is defined as TextView (whose value is auto generated) and the next two columns are EditText (whose value is filled up by the user).
What I want:
I want to add a new row to the ListView whenever:
User hit enter key on any EditText
There is no empty EditText (meaning all the EditText defined so far have some value in them).
Basically I want display a new orders list where users can add orders.
My code so far:
ListView Model:
public class NewTableModel {
private String sNo, product, price;
public NewTableModel(String sNo, String product, String price){
this.sNo = sNo;
this.product = product;
this.price = price;
}
public String getProduct(){ return product; }
public String getPrice(){ return price; }
public String getsNo() { return sNo; }
}
ListView adapter:
public class NewTableAdapter extends BaseAdapter {
private ArrayList<NewTableModel> productList;
private Activity activity;
public NewTableAdapter(Activity activity, ArrayList<NewTableModel> productList) {
super();
this.activity = activity;
this.productList = productList;
}
#Override
public int getCount() { return productList.size(); }
#Override
public Object getItem(int position) { return productList.get(position); }
#Override
public long getItemId(int position) { return position; }
public class ViewHolder {
TextView mSno;
EditText mProduct;
EditText mPrice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.new_table_row, null);
holder = new ViewHolder();
holder.mSno = (TextView) convertView.findViewById(R.id.sno);
holder.mProduct = (EditText) convertView.findViewById(R.id.product);
holder.mPrice = (EditText) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
NewTableModel item = productList.get(position);
holder.mSno.setText(item.getsNo());
holder.mProduct.setText(item.getProduct());
holder.mPrice.setText(String.valueOf(item.getPrice()));
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayList<NewTableModel> productList;
private ListView orderView;
private NewTableAdapter orderAdapter;
private void insertNewRow(){ insertNewRow("",""); }
private void insertNewRow(String productVal, String priceVal){
String serialNoVal = String.valueOf(orderView.getCount() + 1);
NewTableModel item = new NewTableModel(serialNoVal, productVal, priceVal);
productList.add(item);
}
private void setupAdapter(){
productList = new ArrayList<NewTableModel>();
orderView = (ListView) findViewById(R.id.newTableContent);
orderAdapter = new NewTableAdapter(this, productList);
orderView.setAdapter(orderAdapter);
orderAdapter.notifyDataSetChanged();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
setupAdapter();
insertNewRow();
}
}
My Listener:
setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
&& noEmptyColumn())
insertNewRow();
return false;
}
});
Where should I place that listener ? and how would I check if any column is empty or not (define noEmptyColumn()) ?
You should place the listener where any of EditText values are changed. I would add a Button to any row, and set the listener at there. So in your ViewHolder:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean hasEmpty = false;
for (NewTableModel item: productList) {
if (item.getDesiredField().isEmpty()) {
hasEmpty = true;
break;
}
}
if (!hasEmpty) {
insertNewRow();
notifyDataSetChanged();
}
}
});
Another option could be setting a TextWatcher on EditText :
ed.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
boolean hasEmpty = false;
for (NewTableModel item: productList) {
if (item.getDesiredField().isEmpty()) {
hasEmpty = true;
break;
}
}
if (!hasEmpty) {
insertNewRow();
notifyDataSetChanged();
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Just move both methods to your Adapter class. And note that the second solution is not efficient when there are too many rows.

How can I know which row is checked using checkbox and listview?

Below is ListView Item Class
public class CategoryItem06 {
private String text;
private boolean checked;
public void setText(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
// public void setCheck(boolean checked) {
this.checked = checked;
}
// public boolean getCheck() {
return this.checked;
}
}
Below is Adapter
public class CategoryAdapter06 extends BaseAdapter {
public ArrayList<CategoryItem06> listViewItemList = new ArrayList<CategoryItem06>() ;
public CategoryAdapter06() {
}
#Override
public int getCount() {
return listViewItemList.size() ;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
final Context context = parent.getContext();
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_item06, parent, false);
}
TextView textTextView = (TextView) convertView.findViewById(R.id.textView1) ;
CheckBox checkBox=(CheckBox) convertView.findViewById(R.id.checkBoxMafia);
CategoryItem06 listViewItem = listViewItemList.get(position);
textTextView.setText(listViewItem.getText());
checkBox.setChecked(listViewItem.getCheck());
return convertView;
}
#Override
public long getItemId(int position) {
return position ;
}
#Override
public Object getItem(int position) {
return listViewItemList.get(position) ;
}
public void addItem( String text) {
CategoryItem06 item = new CategoryItem06();
item.setText(text);
listViewItemList.add(item);
}
}
Below is Checkable Relative Layout
public class CategoryCheckableRelativeLayout extends RelativeLayout implements Checkable {
public CategoryCheckableRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// mIsChecked = false ;
}
#Override
public boolean isChecked() {
CheckBox cb = (CheckBox) findViewById(R.id.checkBoxMafia);
return cb.isChecked();
// return mIsChecked ;
}
#Override
public void toggle() {
CheckBox cb = (CheckBox) findViewById(R.id.checkBoxMafia);
setChecked(cb.isChecked() ? false : true);
// setChecked(mIsChecked ? false : true) ;
}
#Override
public void setChecked(boolean checked) {
CheckBox cb = (CheckBox) findViewById(R.id.checkBoxMafia);
if (cb.isChecked() != checked) {
cb.setChecked(checked);
}
}
}
Below is Activity that uses ListView
public class CategorySelection06 extends AppCompatActivity {
Singleton s1 = Singleton.getInstance();
ListView listview;
// Creating Adapter
CategoryAdapter06 adapter = new CategoryAdapter06();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_category_selection06);
listview = (ListView) findViewById(R.id.listview1);
listview.setAdapter(adapter);
// Adding Items
adapter.addItem("Pets");
adapter.addItem("Singers");
adapter.addItem("Game");
adapter.addItem("Nations");
Button button = findViewById(R.id.button6);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < adapter.listViewItemList.size(); i++) {
if (adapter.listViewItemList.get(i).getCheck()) {
s1.ListViewCategory.add(adapter.listViewItemList.get(i).getText());
}
}
Intent intent = new Intent(getApplicationContext(), RoleSelection07.class);
startActivity(intent);
finish();
}
});
}
}
My ListView's form is like this: TextView ------- Checkbox
I want to make an Activity like this: if user checks checkbox, then the checked row's text is saved in ArrayList in Singleton class.
For example, if a user checked checkbox of "Pets" and "Nations" then these words goes into the ArrayList s1.ListViewCategory, which is in Singleton class.
I've tried for loops and if statements in CategorySelectionActivity like this:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int i = 0; i < adapter.listViewItemList.size(); i++) {
if (adapter.listViewItemList.get(i).getCheck()) {
s1.ListViewCategory.add(adapter.listViewItemList.get(i).getText());
}
}
Intent intent = new Intent(getApplicationContext(), RoleSelection07.class);
startActivity(intent);
finish();
}
However,getCheck() doesn't work because setCheck() is not in the addItem() in CategoryAdapter class.
I tried to put setCheck() in the addItem() method , but then I have to put another parameter in add(), then I got red lines and errors.
Since I am a novice, I copied these codes from sites, but I don't really get the idea of using CheckableRelativeLayout.
This Layout shows that the checkbox is checked or not, but it doesn't indicate which row is checked.
To sum up, my question is ' how can I get texts from multiple rows that are checked, and know which row is checked ?
I know the question is super long, but I really need to solve this problem...
I will be super grateful if someone answers my question Thank you
Nobody answered so I fixed it by my own.
SparseBooleanArray checkedItems = listview.getCheckedItemPositions();
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
if (checkedItems.get(i)) {
s1.ListViewCategory.add(adapter.listViewItemList.get(i).getText());
}
}
listview.clearChoices();
Intent intent = new Intent(getApplicationContext(), RoleSelection07.class);
startActivity(intent);
finish();

checkbox in listview to select and delete

This is my code I have one list view in the fragment which read sms using cursor I have set check box in adapter and I have 3 buttons outside the list view in main layout I need the followings
1.When I click one button it display checkbox in the list
2.when I select and scroll the list selected items wont disappears
3.select all button to select all in the list 4.delete button to delete the selected item remaining messages instantly updated.
public class TabFragment extends Fragment
{
ListView mlistView;
ArrayList<Message> sms = new ArrayList<Message>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_sms, container, false);
mlistView = (ListView) view.findViewById(R.id.SMSList);
Button sdel=(Button)view.findViewById(R.id.sdelete);
populateMessageList();
sdel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
public void populateMessageList() {
fetchInboxMessages();
if (fetchInboxMessages() != null) {
mlistView.setAdapter(new datalist(getActivity().getApplicationContext(),this));
}
}
public ArrayList<Message> fetchInboxMessages() {
Uri muriSms = Uri.parse("content://sms/inbox");
Cursor mcursor = getActivity().getContentResolver().query(muriSms,
new String[] { "_id", "address", "date", "body" }, null, null,
null);
mcursor.moveToFirst();
while (mcursor.moveToNext()) {
Message mMessage = new Message();
mMessage.setmAddress(mcursor.getString(mcursor
.getColumnIndex("address")));
mMessage.setmBody(mcursor.getString(mcursor.getColumnIndex("body")));
mMessage.setmDate(mcursor.getString(mcursor.getColumnIndex("date")));
sms.add(mMessage);
}
return sms;
}
class datalist extends BaseAdapter {
LayoutInflater inflater = null;
Boolean selected;
Boolean[] checkboxstate;
public datalist(Context applicationContext, TabFragment tabFragment) {
inflater = LayoutInflater.from(applicationContext);
} public datalist(Context applicationContext, int simple_list_item_multiple_choice, ArrayList<Message> sms) {
}
#Override
public int getCount() {
return sms.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row;
row = inflater.inflate(R.layout.sms_adapter, parent, false);
ImageView img1 = (ImageView) row.findViewById(R.id.icon2);
TextView txt1 = (TextView) row.findViewById(R.id.text1);
TextView txt2 = (TextView) row.findViewById(R.id.text2);
CheckBox cb=(CheckBox)row.findViewById(R.id.check);
Long timestamp = Long.parseLong(sms.get(position).getmDate());
Calendar mcalendar = Calendar.getInstance();
mcalendar.setTimeInMillis(timestamp);
DateFormat mformatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
txt1.setText(sms.get(position).getmBody());
txt2.setText("Sent by" + sms.get(position).getmAddress() + "\n" + mformatter.format(mcalendar.getTime()));
/* if(selected==false)
cb.setVisibility(row.GONE);
else*/
cb.setVisibility(row.VISIBLE);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
sms.get(position).setSelected(isChecked);
if(isChecked){
buttonView.setSelected(true);
}else {
buttonView.setSelected(false);
}
}
});
return row;
}
}
public class Message {
private String mAddress;
private String mBody;
private String mDate;
private int icon;
boolean selected;
public void setmAddress(String mAddress) {
this.mAddress = mAddress;
}
public void setmBody(String mBody) {
this.mBody = mBody;
}
public void setmDate(String mDate) {
this.mDate = mDate;
}
public String getmBody() {
return mBody;
}
public String getmAddress() {
return mAddress;
}
public String getmDate() {
return mDate;
}
public boolean isSelected() {
return selected;
}
public int getIcon(){
return icon;} public void setSelected(boolean selected) {
this.selected = selected;
}}}

How to create a Multilevel list using listview

The following is my Json data from database, i want to list the interest_name in a list(only if visible is true). List must be multilevel. I parsed the json file using Gson library. But i have no idea regarding how to make a multilevel list using listview.
{"interest_id":0,"interest_name":"ROOT","visible":false,"children":
[{"interest_id":1,"interest_name":"Sports","visible":true,"children":[{"interest_id":2,"interest_name":"Archery","visible":true,"children":[]},{"interest_id":3,"interest_name":"Bow Hunting","visible":true,"children":[]}]},{"interest_id":100,"interest_name":"Contry","visible":true,"children":[{"interest_id":101,"interest_name":"Afghanistan","visible":true,"children":[]},{"interest_id":102,"interest_name":"Akrotiri","visible":true,"children":[]}]},{"interest_id":1000,"interest_name":"Education","visible":true,"children":[]},{"interest_id":1200,"interest_name":"Entertainment","visible":true,"children":[]},{"interest_id":1400,"interest_name":"Books","visible":true,"children":[]},{"interest_id":1600,"interest_name":"Services","visible":true,"children":[]},{"interest_id":1800,"interest_name":"Fitness","visible":true,"children":[]},{"interest_id":2000,"interest_name":"Fashion","visible":true,"children":[]},{"interest_id":99999,"interest_name":"Near Me","visible":false,"children":[]}]}
My code:
Home.java
Intent intent = new Intent( Home.this,InterestAddList.class);
startActivity(intent);
finish();
InterestAddList.java
public class InterestAddList extends Activity {
ListView intrestListView;
OneOnOneListAdapter adapter;
List<String> intrestList;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intrest_add);
intrestListView = (ListView) findViewById(R.id.InterestList);
//Service Called For retrieving Data
retrieveList();
}
public void retrieveList() {
intrestList = new ArrayList<String>();
StringBuilder urlc = new StringBuilder(urlPrefix + "gai");
String url=urlc.toString();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String result = ServiceClient.getInstance().getResponse(url);
InterestNode ni=gson.fromJson(result, InterestNode.class);
//for(int i=0;i<ni.length;i++){
//Log.e("ni", ni.getInterestName());
//Log.e("ni", String.valueOf(ni.getInterestId()));
/* how to display interest name */
intrestList.add(ni.getInterestName());
}
adapter = new OneOnOneListAdapter(InterestAddList.this,R.layout.intrest_add_row,intrestList);
intrestListView.setAdapter(adapter);
}
private class OneOnOneListAdapter extends ArrayAdapter {
public OneOnOneListAdapter(Context context, int textViewResourceId,
List objects) {
super(context, textViewResourceId, objects);
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final int aposition=position;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.intrest_add_row, null);
}
TextView intrestText =(TextView)v.findViewById(R.id.IntrestText);
intrestText.setText(intrestList.get(aposition).toString());
v.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
System.out.println("OnItem CLicked");
Toast.makeText(InterestAddList.this,"Position clicked:"+intrestList.get(aposition).toString(),Toast.LENGTH_SHORT).show();
Intent i = new Intent(InterestAddList.this,SubIntrestAddList.class);
i.putExtra("position", aposition);
startActivityForResult(i,1);
}
});
return v;
}
}}
InterestNode.java
public class InterestNode {
#SerializedName("interest_id")
int interestId;
#SerializedName("interest_name")
String interestName;
#SerializedName("visible")
boolean isVisible;
transient InterestNode parent;
#SerializedName("children")
List<InterestNode> childList = new ArrayList<InterestNode>();
public List<InterestNode> getChildren(){
return new ArrayList<InterestNode>(childList);
}
public int getInterestId() {
return interestId;
}
public String getInterestName() {
return interestName;
}
public InterestNode getParent() {
return parent;
}
public boolean isVisible() {
return isVisible;
}
public void addChild(InterestNode intNode){
childList.add(intNode);
}
public void setInterestId(int interestId) {
this.interestId = interestId;
}
public void setInterestName(String interestName) {
this.interestName = interestName;
}
public void setParent(InterestNode parent) {
this.parent = parent;
}
public void setVisible(boolean isVisible) {
this.isVisible = isVisible;
}
}
It better to use Expandable ListView to add multilevel list, instead. But you want using listview then follow below nice tutorial here step by step three level listiview is achieved.
Android Multilevel ListView Tutorial
hope it helps you!

Selection of all check boxes in listview

I want to select all check boxes in a listview but I'm not able to get checkbox objects from the listview. I can select a single check box but not multiple check boxes.
Your suggestion are appreciable.
Code:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bir);
mainListView = (ListView) findViewById(R.id.mainListView);
selectall = (Button) findViewById(R.id.button1);
selectall.setOnClickListener(this);
save = (Button) findViewById(R.id.button2);
save.setOnClickListener(this);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {
}
});
}
}
class Amphian:
private static class Amphian
{
private String name = "" ;
private boolean checked = false ;
public Amphian( String name )
{
this.name = name ;
}
public Amphian( String name, boolean checked )
{
this.name = name ;
this.checked = checked ;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
#Override
public String toString() {
return name ;
}
public void toggleChecked()
{
checked = !checked ;
}
}
class AmphiansArrayAdapter:
public class AmphiansArrayAdapter extends ArrayAdapter<Amphian>
{
Integer name[] =
{
R.raw.ducks_landing_in_water,
R.raw.flicker_chicks_feeding,
R.raw.geese_honking_loud,
R.raw.geese_honking_distant,
R.raw.gold_finch,
R.raw.humming_bird_feeding,
R.raw.indigo_bunting,
R.raw.loons,
R.raw.little_blue_heron_fishing,
R.raw.pelican_chick,
R.raw.purple_martins,
R.raw.red_winged_blackbird,
R.raw.shorebirds_close,
R.raw.shorebirds_distant,
R.raw.shorebirds_misc,
R.raw.shoreseabirds,
R.raw.snow_geese_flock,
R.raw.terns,
R.raw.tufted_titmouse,
R.raw.tundra_swans,
R.raw.wood_stork_chicks,
R.raw.woodpecker_tapping
};
private final LayoutInflater inflater;
public AmphiansArrayAdapter(Context context, List<Amphian> amphianList)
{
super( context, R.layout.simplerow, R.id.rowTextView, amphianList );
inflater = LayoutInflater.from(context) ;
}
#Override
public View getView( final int position, View convertView , ViewGroup parent)
{
final Amphian amphian=this.getItem(position);
mp=new MediaPlayer();
if ( convertView == null )
{
convertView = inflater.inflate(R.layout.simplerow, null);
// Find the child views.
textView = (TextView) convertView.findViewById( R.id.rowTextView );
checkBox = (CheckBox) convertView.findViewById( R.id.checkBox1 );
button = (Button)convertView.findViewById(R.id.button1);
// Optimization: Tag the row with it's child views, so we don't have to
// call findViewById() later when we reuse the row.
convertView.setTag( new AmphianViewHolder(textView,checkBox,button) );
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener( new View.OnClickListener()
{
#Override
public void onClick(View v)
{
cb= (CheckBox) v;
Log.e("cb",String.valueOf(cb));
Amphian amphian = (Amphian) cb.getTag();
Log.e("cb",String.valueOf(cb.getTag()));
amphian.setChecked(cb.isChecked());
Log.e("dd", "ddd");
}
});
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Button bu=(Button)v;
Amphian amphian;
//= (Amphian) bu.getTag();
//Log.e(String.valueOf(amphian),"ddd");
Try this.
public class MainActivity extends Activity implements OnClickListener {
public class LVSample3Adapter extends BaseAdapter{
private Context context;
private List<LVSample3Item> itemList;
public LVSample3Adapter(List<LVSample3Item> lstItems,
MainActivity mainActivity) {
// TODO Auto-generated constructor stub
this.context=mainActivity;
this.itemList=lstItems;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.e("lstItems1:", String.valueOf(position));
LVSample3Item item = itemList.get(position);
convertView =LayoutInflater.from(context).inflate(R.layout.list, parent, false);
TextView t1=(TextView)convertView.findViewById(R.id.textView1);
t1.setText(item.getTitle());
CheckBox chb1=(CheckBox)convertView.findViewById(R.id.checkBox1);
chb1.setChecked(item.getstate());
return convertView;
}
}
/** Called when the activity is first created. */
private ListView lv;
private ListAdapter adapter;
private Button btn1,btn2;
private List<LVSample3Item> lstItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1=(Button)findViewById(R.id.button1);
btn2=(Button)findViewById(R.id.button2);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
lstItems = new ArrayList<LVSample3Item>();
LVSample3Item item = new LVSample3Item("drinks",false);
lstItems.add(item);
item = new LVSample3Item("chat",false);
lstItems.add(item);
item = new LVSample3Item("chat1",true);
lstItems.add(item);
item = new LVSample3Item("chat2",false);
lstItems.add(item);
adapter = new LVSample3Adapter(lstItems, this);
lv=(ListView)findViewById(R.id.listView1);
lv.setAdapter(adapter);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==R.id.button1){
Log.e("lstItems:", String.valueOf(lstItems.size()));
for(int i=0;i<lstItems.size();i++){
LVSample3Item item=lstItems.get(i);
if(!item.getstate()){
item.setpath(true);
}
}
((BaseAdapter) adapter).notifyDataSetChanged();
}else if(v.getId()==R.id.button2){
for(int i=0;i<lstItems.size();i++){
LVSample3Item item=lstItems.get(i);
if(item.getstate()){
item.setpath(false);
}
}
((BaseAdapter) adapter).notifyDataSetChanged();
}
}
}
public class LVSample3Item implements Serializable {
private String title;
private boolean state;
public LVSample3Item(String title,boolean imagepath) {
this.title = title;
this.state=imagepath;
}
public String getTitle() {
return title;
}
public boolean getstate() {
return state;
}
public void setTitle(String title) {
this.title = title;
}
public void setpath(boolean imagepath) {
this.state = imagepath;
}
}
There is too much code to read, so I give you a sample how to do that:
int count = list.getCount();
for (int i = 0; i < count; i++) {
View child = list.getItemAtPosition(i);
//check that child..
}
or
int count = list.getChildCount();
for (int i = 0; i < count; i++) {
View child = list.getChildAt(i);
//check that child..
}
selectall.setOnClickListener(new onClickListener(){
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
list.getItem(i).setChecked(true);
}
}
});
try doing soething like this

Categories

Resources