I am using the base adapter , i have list which contains list with the text view (means left side sent items and below to that ,right side received items, i want to click on the each position in the list to perform replying the messaging .
Please suggest me how do i perform the function on clicking the listitem
Below is the code ,which i am using
class MessageAdapter extends BaseAdapter {
ViewHolder viewHolder;
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
public int getCount() {
// TODO Auto-generated method stub
return Constant_Variables.Sms_Status_list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.messagelist_row, null);
viewHolder=new ViewHolder();
viewHolder.sms_from_row=(TextView)convertView.findViewById(R.id.sms_from_txtview);
viewHolder.sms_to_row=(TextView)convertView.findViewById(R.id.sms_sendto_txtview);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.sms_from_row.setVisibility(View.VISIBLE);
viewHolder.sms_to_row.setVisibility(View.VISIBLE);
if(Constant_Variables.Sms_Status_list.get(position).equalsIgnoreCase(Twilioresponse_Utils.sms_sent))
{
viewHolder.sms_from_row.setVisibility(View.GONE);
viewHolder.sms_to_row.setText("Sent: "+Constant_Variables.Sms_from_list.get(position));
}
else if(Constant_Variables.Sms_Status_list.get(position).equalsIgnoreCase(Twilioresponse_Utils.sms_received))
{
viewHolder.sms_to_row.setVisibility(View.GONE);
viewHolder.sms_from_row.setText("Received: "+Constant_Variables.Sms_to_list.get(position));
}
else
{
viewHolder.sms_from_row.setText("Message in queued.");
viewHolder.sms_to_row.setVisibility(View.VISIBLE);
}
convertView.setTag(viewHolder);
return convertView;
}
protected void onListItemClick(ListView l, View v, final int position, long id) {
if(l.callOnClick()== true)
{
Log.i("the Item clicked is at position : ", ""+ position);
}
else
{
Log.i("the Item not clicked is at position : ","the Item not clicked is at position" );
}
}
}
Below is the XML code which i am using
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/sms_from_txtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:layout_alignParentRight="true"
android:background="#drawable/blue"
android:layout_alignParentTop="true"
android:text="From" />
<TextView
android:id="#+id/sms_sendto_txtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="12dp"
android:background="#drawable/red"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="To" />
</RelativeLayout >
Regards
Amrinder Singh
there is onItemClickListener in android, you can use that
ListView listview = (ListView)findViewById(R.id.yourlist);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// #todo
}
});
For individual view in you list item, you can always add click listener in getView method.
Implement click listener for both when you initialize that view
viewHolder.sms_from_row.setOnClickListener(new OnClickListener(){
public void onClick(View view){
// Todo thing
}
});
viewHolder.sms_to_row.setOnClickListener(new OnClickListener(){
public void onClick(View view){
// Todo thing
}
});
Write on item click on textview
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.messagelist_row, null);
viewHolder=new ViewHolder();
viewHolder.sms_from_row=(TextView)convertView.findViewById(R.id.sms_from_txtview);
viewHolder.sms_to_row=(TextView)convertView.findViewById(R.id.sms_sendto_txtview);
viewHolder.sms_from_row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.sms_from_row.setVisibility(View.VISIBLE);
viewHolder.sms_to_row.setVisibility(View.VISIBLE);
if(Constant_Variables.Sms_Status_list.get(position).equalsIgnoreCase(Twilioresponse_Utils.sms_sent))
{
viewHolder.sms_from_row.setVisibility(View.GONE);
viewHolder.sms_to_row.setText("Sent: "+Constant_Variables.Sms_from_list.get(position));
}
else if(Constant_Variables.Sms_Status_list.get(position).equalsIgnoreCase(Twilioresponse_Utils.sms_received))
{
viewHolder.sms_to_row.setVisibility(View.GONE);
viewHolder.sms_from_row.setText("Received: "+Constant_Variables.Sms_to_list.get(position));
}
else
{
viewHolder.sms_from_row.setText("Message in queued.");
viewHolder.sms_to_row.setVisibility(View.VISIBLE);
}
convertView.setTag(viewHolder);
return convertView;
}
Your code is right just add the click listener below this.
viewHolder.sms_from_row=(TextView)convertView.findViewById(R.id.sms_from_txtview);
viewHolder.sms_to_row=(TextView)convertView.findViewById(R.id.sms_sendto_txtview);
Below this add click listener like this.
viewHolder.sms_from_row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
viewHolder.sms_to_row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Hope it help you.
Thanks.
When clicked on list
Clicked on Delete icon
here is the code you can refer:
public class CaseAdapter extends BaseAdapter{
Context context;
ArrayList<PojoClass> list;
LayoutInflater inflater;
public CaseAdapter(Context context,ArrayList<PojoClass> list)
{
this.context=context;
this.list=list;
inflater=(LayoutInflater)this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if(row == null)
{
row = inflater.inflate(R.layout.activity_home_screen, parent,false);
holder = new ViewHolder(row);
row.setTag(holder);
}
else
{
holder = (ViewHolder) row.getTag();
}
holder.caseNumber.setText(list.get(position).getCaseNo());
holder.state.setText(list.get(position).getState());
holder.date.setText(list.get(position).getDate());
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "record clicked!", Toast.LENGTH_LONG).show();
}
});
holder.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
v=(View) v.getParent();//utilizing the View object...or we can use new view object
//View view=(View)v.getParent();//this one also we can use...but instead of v object you need to use view object;
TextView number=(TextView)v.findViewById(R.id.textView_case_number);
InfoDb db=new InfoDb(context);//using for remove record from database
db.open();
if(db.removeRecord(number.getText().toString()))
{
list.remove(position);
Toast.makeText(context, "Record Deleted!", Toast.LENGTH_LONG).show();
CaseAdapter.this.notifyDataSetChanged();
}else
Toast.makeText(context, "Record not Deleted!", Toast.LENGTH_LONG).show();
db.close();
}
});
return row;
}
public class ViewHolder{
TextView state,caseNumber,date;
ImageView delete;
public ViewHolder(View v){
state=(TextView)v.findViewById(R.id.textView_State);
caseNumber=(TextView)v.findViewById(R.id.textView_case_number);
date=(TextView)v.findViewById(R.id.textView_date);
delete=(ImageView)v.findViewById(R.id.ImageView_Delete);
}
}
}
Related
I have use this class extends base adapter display values. Below code working eclipse correctly. but me newly created project using Androi Studio there this code getview function not call or working.
i also check getcount . getcount values available.
public class CustomAdapterChatActivity extends BaseAdapter {
ArrayList<ChatUsersDetailsBean> mBeans = new ArrayList<ChatUsersDetailsBean>();
Context mcontext;
LayoutInflater inflater;
CommonUtil commonUtil;
public CustomAdapterChatActivity(Context context,
ArrayList<ChatUsersDetailsBean> mBeans) {
// TODO Auto-generated constructor stub
mcontext = context;
this.mBeans = mBeans;
commonUtil = new CommonUtil(context);
inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mBeans.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView name;
TextView content;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.e("getView",""+"getView");
if (convertView == null) {
convertView = inflater.inflate(
R.layout.chat_listview_layout_screen, null);
}
setAttributes(position, convertView);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
click(position);
}
});
return convertView;
}
public void click(int position) {
Intent mintent = new Intent(mcontext, ChatViewBackgroundActivity.class);
mintent.putExtra("name", mBeans.get(position).getOpponent_name());
((ChatActivity) mcontext).startActivityForResult(mintent, 1);
}
public void setAttributes(final int position, View convertView) {
Holder holder = new Holder();
holder.imgdispatcher = (ImageView) convertView
.findViewById(R.id.chat_list_iv_profilepic);
}
Please help me. i struggle this part.
No error will be displayed.
i check getview run or not that time getview not working anytime.
this code any changes needed
Change your getView() method in your adapter class like below code:
public View getView (final int position, View convertView, ViewGroup parent){
if( convertView == null ){
//We must create a View:
convertView = inflater.inflate(R.layout.my_list_item, parent, false);
}
//Here we can do changes to the convertView
return convertView;
}
While adding newly inflated view, try to avoid passing null as view root. Lint will now warn you not to pass in null for root. Your app won’t crash in this scenario, but it can misbehave. When your child View doesn’t know the correct LayoutParams for its root ViewGroup, it will try to determine them on its own using generateDefaultLayoutParams.
#AbiK If you already done like I mentioned on above comment means, use below code of modified getView() method and setAttributes() method. I hope It works for you.
public class CustomAdapterChatActivity extends BaseAdapter {
ArrayList<ChatUsersDetailsBean> mBeans;
Context mcontext;
LayoutInflater inflater;
CommonUtil commonUtil;
public CustomAdapterChatActivity(Context context,
ArrayList<ChatUsersDetailsBean> mBeans) {
mcontext = context;
this.mBeans = mBeans;
commonUtil = new CommonUtil(context);
}
#Override
public int getCount() {
return mBeans.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView name;
TextView content;
ImageView imgdispatcher;
}
public Holder setAttributes(final int position, View convertView) {
Holder holder = new Holder();
holder.imgdispatcher = (ImageView) convertView.findViewById(R.id.chat_list_iv_profilepic);
// holder.name=(TextView)convertView.findViewById(R.id.); // declare Id
// holder.content=(TextView)convertView.findViewById(R.id.); // declare Id
return holder;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder = null;
LayoutInflater inflater = (LayoutInflater)
mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.chat_listview_layout_screen, parent, false);
holder = setAttributes(position, convertView);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
click(position);
}
});
return convertView;
}
public void click(int position) {
Intent mintent = new Intent(mcontext, ChatViewBackgroundActivity.class);
mintent.putExtra("name", mBeans.get(position).getOpponent_name());
((ChatActivity) mcontext).startActivityForResult(mintent, 1);
}
}
Here's the code of my baseadapter which shows contacts' name, phone number and checkboxes alongside them.
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ public SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
int mPos;
MyAdapter()
{
if (mCheckStates==null){
mCheckStates = new SparseBooleanArray(name1.size());
}else {
mCheckStates = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");
}
mInflater = (LayoutInflater) ContactActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
public void setPosition(int p){
mPos = p;
}
public int getPosition(){
return mPos;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
setPosition(position);
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
Activity code:
#Override
public void onDestroy(){
bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
//adapter is the MyAdapter object created in parent class
super.onDestroy();
}
Note that I'm using bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates)); and mCheckStates = (SparseBooleanArray) bundle.getParcelable("myBooleanArray");, to store and retrieve the SparseBooleanArray on activity being destroyed and recreated. The onDestroy() method is of the parent class, which is an activity. I haven't pasted that, because I thought it was irrelevant. Please ask if it's needed.
I'm also using a SparseBooleanArrayParcelable class that helps me mCheckStates on destruction, and retrieve on creation.
According to the logs, the NullPointerException occurs within onDestroy() when trying to execute bundle.putParcelable("myBooleanArray", new SparseBooleanArrayParcelable(adapter.mCheckStates));
Help will be appreciated. Thank you!
EDIT: I had initialized bundle wrong. Now I do not get any sort of errors, but the checkbox state isn't saved. I could use some help with that. Thank you!
I have a Button inside a ListView.
I want to go to another Activity when it is clicked.
But I get this error:
No enclosing instance of the type Appointment is accessible in scope
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
TextView txtsection = (TextView)vi.findViewById(R.id.section);
TextView txtdoctor = (TextView)vi.findViewById(R.id.doctor);
TextView txtdate = (TextView)vi.findViewById(R.id.date);
TextView txttime = (TextView)vi.findViewById(R.id.time);
btchange = (Button)vi.findViewById(R.id.change);
btchange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context, Available.class);
startActivity(i);
}
});
btdelete = (Button)vi.findViewById(R.id.delete);
txtsection.setText(item.section);
txtdoctor.setText(item.doctor);
txtdate.setText(item.date);
txttime.setText(item.time);
return vi; }}
At line
Intent i = new Intent(Appointment.this,Available.class);
Appointment.this is valid only if the adaptar is an inner class of Appointment.
If is not the case, use the Context passed to the adapter.
Intent i = new Intent(context, Available.class);
Declare a private field, named context, in your adapter:
private Context context;
In the adapter constructor, assign the context passed to it:
this.context = context;
Change the getView method to this:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if( convertView == null ){
convertView = inflater.inflate(R.layout.yourListLayout, parent, false);
}
Button btchange = (Button)convertView.findViewById(R.id.yourbuttonid);
btchange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context, Available.class);
startActivity(i);
}
});
return convertView;
}
EDIT
btChange also need to point to the button that has clicked as playmaker420 said.
I edited the code to accomplish that.
EDIT 2
Change your code adapter to this:
package com.example.clinic;
public class CustomListViewAdapter extends BaseAdapter
{
private Context context;
Button btchange,btdelete;
LayoutInflater inflater;
List<ListViewItem> items;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.context = context;
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
//add
ListViewItem item = items.get(position);
TextView txtsection = (TextView)vi.findViewById(R.id.section);
TextView txtdoctor = (TextView)vi.findViewById(R.id.doctor);
TextView txtdate = (TextView)vi.findViewById(R.id.date);
TextView txttime = (TextView)vi.findViewById(R.id.time);
btchange = (Button)vi.findViewById(R.id.change);
btchange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context, Available.class);
//updated
context.startActivity(i);
}
});
btdelete = (Button)vi.findViewById(R.id.delete);
txtsection.setText(item.section);
txtdoctor.setText(item.doctor);
txtdate.setText(item.date);
txttime.setText(item.time);
return vi;
}
Intent i = new Intent(Appointment.this,Available.class);
startActivity(i);
public class AppleSupportList extends BaseAdapter {
private LayoutInflater mInflater;
private final String[] values;
public AppleSupportList(Context context, String[] values) {
mInflater = LayoutInflater.from(context);
this.values = values;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return values.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.customlist1, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.labelContact1);
holder.img = (ImageView) convertView.findViewById(R.id.imageContact1);
holder.check = (CheckBox) convertView.findViewById(R.id.checkBoxContact1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text1.setText(values[position]);
holder.check.setId(position);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.check.isChecked()) {
holder.check.setChecked(false);
//store id
} else {
holder.check.setChecked(true);
//remove id
}
}
});
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
if (cb.isChecked()) {
//store id
} else {
//remove id
}
}
});
return convertView;
}
static class ViewHolder {
TextView text1;
ImageView img;
CheckBox check;
}
}
i am creating a custom list view with check boxes.all works fine except when i scroll the list the check boxes get checked/unchecked automatically.
How can i store the state of check boxes.
I have gone through all related questions but nothing worked for me.
Please take a look at my code and help me out.
Your Custom Adapter must implement CompoundButton.OnCheckedChangeListener. Use a SparseBooleanArray.
Drawing from Romain guy's solution #
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
Then
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
Then use the checked state to set text to check box
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
Use the below example as reference and modify according your requirements. I have not used a viewholder in the sample. Use a view holder as you used in your code.
Example
public class MainActivity extends Activity implements
AdapterView.OnItemClickListener {
int count;
private CheckBoxAdapter mCheckBoxAdapter;
String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView listView = (ListView) findViewById(R.id.lv);
listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
for(int i=0;i<GENRES.length;i++)
{
if(mCheckBoxAdapter.mCheckStates.get(i)==true)
{
result.append(GENRES[i]);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 1000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int
position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
String[] gen;
CheckBoxAdapter(MainActivity context, String[] genres)
{
super(context,0,genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen= genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.checkbox, null);
tv= (TextView) vi.findViewById(R.id.textView1);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ gen [position]);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
I have a ListViewwhich has a custom cell in it with 2 buttons, a label and an editText. I've got it so that when I click the button for the custom cell it does a log saying at what position the button has been pressed. However I can't work out how I make it so when I press the button, it changes the text in the textbox for that cell. I can't work out how to reference it at a position.
My XML is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/lvItems"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:drawSelectorOnTop="false" >
</ListView>
</RelativeLayout>
My Code:
class CustomAdapter extends BaseAdapter
{
#Override
public int getCount() {
return mDescription.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
LayoutInflater inf=getLayoutInflater();
View v=inf.inflate(R.layout.noncriticalasset, arg2,false);
TextView tv=(TextView)v.findViewById(R.id.txtOption);
final EditText et =(EditText)v.findViewById(R.id.tbAnswer);
Button btPlus=(Button)v.findViewById(R.id.btnPlus);
Button btMinus=(Button)v.findViewById(R.id.btnMinus);
btMinus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
int position = listView
.getPositionForView((View) v.getParent());
Log.v("Position id", "" + position);
et.setText("Test Text");
notifyDataSetChanged();
} catch (Exception e) {
Log.e("error", "error" + e.getMessage());
}
}
});
tv.setText(mDescription.get(arg0).toString());
return v;
}
I tried referencing the textbox with just an et.setText() but it didn't work. Is there a way to say atPosisiton.et.setText etc?
Thanks a lot.
First of all I would insist you to use recycling pattern of ListView, which will work faster as it reduces the creation of the ListView row item views everytime when ListView scroll and re-uses the already created/instantiated view. And for maintaining the value of EditText/CheckBox you have to use setTag() for maintaining its position when ListView scrolls. I had written a blog post for the same here.
hi declare Button in Adapter not in get view and ViewHolder. like below
Button btPlus,btMinus;
ViewHolder holder ;
class ViewHolder {
int fieldPossition;
}
#Override
public View getView(int position, View v, ViewGroup arg2) {
holder = new ViewHolder();
LayoutInflater inf=getLayoutInflater();
v=inf.inflate(R.layout.noncriticalasset, arg2,false);
TextView tv=(TextView)v.findViewById(R.id.txtOption);
EditText et =(EditText)v.findViewById(R.id.tbAnswer);
btPlus=(Button)v.findViewById(R.id.btnPlus);
btMinus=(Button)v.findViewById(R.id.btnMinus);
fieldPossition = position;
btMinus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
ViewHolder deleteHolder = (ViewHolder) v.getTag();
//
int pos = deleteHolder.fieldpossition;
Log.v("Position id", "" + position);
et.setText("Test Text");
notifyDataSetChanged();
} catch (Exception e) {
Log.e("error", "error" + e.getMessage());
}
}
});
tv.setText(mDescription.get(position).toString());
btMinus.setTag(holder);
return v;
}
thats it .
Actually the position you got is right,but with notifyDataSetChanged() called, ListView will use getView() method to replace all item views with new ones.
So,you should keep the clicked position somewhere ,and setup the EditText in getView().
EDIT Tested OK
LazyViewHolder.class
public class LazyViewHolder {
private EditText et;
private TextView text;
private Button btnSub;
public LazyViewHolder() {
// TODO Auto-generated constructor stub
}
LazyViewHolder(TextView textView,EditText ed,Button btn) {
super();
this.setEt(ed);
this.setText(textView);
this.setBtnSub(btn);
}
public EditText getEt() {
return et;
}
public void setEt(EditText et) {
this.et = et;
}
public TextView getText() {
return text;
}
public void setText(TextView text) {
this.text = text;
}
public Button getBtnSub() {
return btnSub;
}
public void setBtnSub(Button btnSub) {
this.btnSub = btnSub;
}
}
getView()in Custom Adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
final TextView textView;
final EditText et;
final Button sub;
if (v == null) {
v = inflater.inflate(R.layout.row, null);
textView = (TextView) v.findViewById(R.id.tvLabel);
textView.setText("Hello"+position);
et = (EditText) v.findViewById(R.id.etWhatToFill);
sub = (Button) v.findViewById(R.id.btnSubmit);
v.setTag(new LazyViewHolder(textView, et, sub));
sub.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(et.getText().toString());
}
});
} else {
LazyViewHolder viewHolder = (LazyViewHolder) v.getTag();
sub = viewHolder.getBtnSub();
et=viewHolder.getEt();
textView = viewHolder.getText();
}
return v;
}
Please Find Detailed Explanation for ListView and CustomListView here