I have a 'row' view, which has two text views and one check-box. I am trying to implement it so that when the checkbox is clicked on, it displays the strings of the two text views in the same row.
I have implemented a for loop to get the parent of the checkbox view, then iterate all the parent views children and get the strings from inside them. But instead of the text I am getting an empty Toast message.
My first class code:
public class InteractiveArrayAdapter extends ArrayAdapter<model> implements
OnClickListener {
private final List<model> list;
private final Activity context;
public InteractiveArrayAdapter(Activity context, List<model> list) {
super(context, R.layout.rep, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.rep, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.TextView07);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.CheckBox05);
view.getParent();
viewHolder.checkbox
.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onClick(View v) {
boolean h = ((CompoundButton) v).isChecked();
model element = (model) viewHolder.checkbox
.getTag();
element.setSelected(h);
ViewGroup row = (ViewGroup) viewHolder.checkbox
.getParent();
for (int itemPos = 0; itemPos < ((ViewGroup) row)
.getChildCount(); itemPos++) {
View view = ((ViewGroup) row)
.getChildAt(itemPos);
if (view instanceof TextView) {
viewHolder.text = (TextView) view; //Found it!
Toast.makeText(context,
viewHolder.text.getText(), 10000)
.show();
break;
}
}
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getName());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
My second class model :
public class ListActivity1 extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list);
// Create an array of Strings, that will be put to our ListActivity
InteractiveArrayAdapter adapter = new InteractiveArrayAdapter(this,
getModel());
setListAdapter(adapter);
}
private List<model> getModel() {
List<model> list = new ArrayList<model>();
list.add(get("Linux"));
list.add(get("Windows7"));
list.add(get("Suse"));
list.add(get("Eclipse"));
list.add(get("Ubuntu"));
list.add(get("Solaris"));
list.add(get("Android"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
list.add(get("iPhone"));
// Initially select one of the items
list.get(1).setSelected(true);
return list;
}
private model get(String s) {
return new model(s);
}
}
Can any one help?
pls try this adapter instead of your custom adapter.
public class ListAdapter<T extends BaseEntity> extends ArrayAdapter {
#SuppressWarnings("unused")
private final List<T> objects;
private Activity activity;
private final List<T> checkboxStatusListOfObject;
private OnClickListener listener;
#SuppressWarnings("unchecked")
public ListAdapter(Activity activity, List<T> objects,
OnClickListener listener, List<T> checkboxStatusListOfObject) {
super( R.layout.simple_row_checkbox_1_item_listview , objects);
this.objects = objects;
this.activity = activity;
this.listener = listener;
this.checkboxStatusListOfObject = checkboxStatusListOfObject;
getFilter();
}
#SuppressWarnings("unchecked")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ObjectViews sqView = null;
if(rowView == null)
{
// Get a new instance of the row layout view
LayoutInflater inflater = this.activity.getLayoutInflater();
rowView = inflater.inflate(R.layout.YourCustomLAyout, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sqView = new ObjectViews();
sqView.checbox = (CheckBox) rowView.findViewById(R.id.checkbox);
if(this.listener !=null){
sqView.checbox.setOnClickListener( this.listener);
}
sqView.text1 = (TextView) rowView.findViewById(R.id.text);
sqView.dataObject = new Object();
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sqView);
} else {
sqView = (ObjectViews) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
T object = (T) objects.get(position);
sqView.text1.setText(object.toString());
sqView.checbox.setText("");
sqView.checbox.setTag(sqView);
sqView.dataObject = object;
if(sqView.getChecbox().isChecked()){
if(this.checkboxStatusListOfObject.indexOf( sqView.dataObject) != -1 ){
sqView.getChecbox().setChecked(true);
}
else{
sqView.getChecbox().setChecked(false);
}
}
return rowView;
}
public class ObjectViews {
Object dataObject;
CheckBox checbox;
TextView text1;
public Object getDataObject() {
return dataObject;
}
public void setDataObject(Object dataObject) {
this.dataObject = dataObject;
}
public CheckBox getChecbox() {
return checbox;
}
public void setChecbox(CheckBox checbox) {
this.checbox = checbox;
}
public TextView getText1() {
return text1;
}
public void setText1(TextView text1) {
this.text1 = text1;
}
}
Define your listener in activity and send to adapter.
OnClickListener listener = new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
// here your code
if(cb.isChecked()){
ObjectViews object = (ObjectViews) cb.getTag();
String text = object.getText1().getText();
Toast.makeText(context,text, Toast.LENGTH_LONG).show();
}
}
};
//you can configure this adapter constructor. this is only example
yourListView.setAdapter(
new ListAdapter(getApplicationContext(), yourObjectList
listener, YourSelectedObjectList));
and layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="6dip"
android:paddingTop="4dip" >
<CheckBox
android:id="#+id/checkbox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20dp" />
<TextView
android:id="#+id/text"
android:layout_width="0dp"
android:layout_marginLeft="10dp"
android:layout_height="wrap_content"
android:layout_weight="4"
android:textSize="20dp" />
</LinearLayout>
Related
The following code is a list of items taken from the database that should I selected objects and display them in another listview by pressing a button.
Please help me with advice given situation. Thanks!
public class ParticipantsSelectedActivity extends AppCompatActivity implements View.OnClickListener{
DataBaseHandler myDb;
ListView listViewParticipants;
ParticipantsSelectedListAdapter participantsSelectedListAdapter;
Participants participants;
Button btn_save_participants_selected;
CheckBox ckb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_participants_selected);
myDb = new DataBaseHandler(this);
ckb = (CheckBox)findViewById(R.id.ckb);
listViewParticipants = (ListView) findViewById(R.id.listViewParticipantsSelected);
btn_save_participants_selected = (Button) findViewById(R.id.btn_save_participants_selected);
final ArrayList<Participants> listData = new ArrayList<>();
final Cursor cursor = myDb.getListParticipants();
if(cursor.getCount() == 0){
Toast.makeText(this, "There is no participants", Toast.LENGTH_SHORT).show();
}else {
while(cursor.moveToNext()){
int id =(Integer.valueOf(cursor.getString(0)));
String firstName = cursor.getString(1);
String position = cursor.getString(3);
participants = new Participants(id,firstName,position, true);
listData.add(participants);
participantsSelectedListAdapter = new ParticipantsSelectedListAdapter(this,android.R.layout.simple_list_item_multiple_choice,listData);
listViewParticipants.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewParticipants.setAdapter(participantsSelectedListAdapter);
btn_save_participants_selected.setOnClickListener(this);
}
}
/*
listViewParticipants.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Participants participants = listData.get(position);
Toast.makeText(getApplicationContext(), "Clicked on Id..." + participants.getId(), Toast.LENGTH_SHORT).show();
}
});
*/
}
#Override
public void onClick(View v) {
//another activity to fill another listView
}
}
This is the custom adapter
public class ParticipantsSelectedListAdapter extends ArrayAdapter<Participants> {
public ParticipantsSelectedListAdapter(Context context,int a, ArrayList<Participants> participants) {
super(context, 0, participants);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Participants participants = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_participants_selected, parent, false);
}
// Lookup view for data population
TextView tvFirstName = (TextView) convertView.findViewById(R.id.tvFirstName);
TextView tvPosition = (TextView) convertView.findViewById(R.id.tvPosition);
CheckBox ckb = (CheckBox) convertView.findViewById(R.id.ckb);
// Populate the data into the template view using the data object
tvFirstName.setText(participants.getFirstName());
tvPosition.setText(participants.getPosition());
ckb.setChecked(false);
// Return the completed view to render on screen
return convertView;
}
}
And this is the XML item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false"
android:id="#+id/ckb"/>
<TextView
android:id="#+id/tvFirstName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvPosition"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In your model class for Participant add one boolean variable like this for making selection and deselection:
In Participant.class
private boolean isSelected;
public void setSelected(boolean selection){
this.isSelected = selection;
}
public boolean isSelected(){
this.isSelected;
}
On database data retrieve you are setting adapter again and again that is wrong, no need to do.
OnClick event added for getting selected items from participants list.
public class ParticipantsSelectedActivity extends AppCompatActivity implements View.OnClickListener {
DataBaseHandler myDb;
ListView listViewParticipants;
ParticipantsSelectedListAdapter participantsSelectedListAdapter;
Participants participants;
Button btn_save_participants_selected;
CheckBox ckb;
final ArrayList<Participants> listData = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_participants_selected);
myDb = new DataBaseHandler(this);
ckb = (CheckBox) findViewById(R.id.ckb);
listViewParticipants = (ListView) findViewById(R.id.listViewParticipantsSelected);
btn_save_participants_selected = (Button) findViewById(R.id.btn_save_participants_selected);
final Cursor cursor = myDb.getListParticipants();
if (cursor.getCount() == 0) {
Toast.makeText(this, "There is no participants", Toast.LENGTH_SHORT).show();
} else {
while (cursor.moveToNext()) {
int id = (Integer.valueOf(cursor.getString(0)));
String firstName = cursor.getString(1);
String position = cursor.getString(3);
participants = new Participants(id, firstName, position, true);
listData.add(participants);
}
//Setting adapter after all data retrieve from database
participantsSelectedListAdapter = new ParticipantsSelectedListAdapter(this, android.R.layout.simple_list_item_multiple_choice, listData);
listViewParticipants.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listViewParticipants.setAdapter(participantsSelectedListAdapter);
btn_save_participants_selected.setOnClickListener(this);
}
/*
listViewParticipants.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Participants participants = listData.get(position);
Toast.makeText(getApplicationContext(), "Clicked on Id..." + participants.getId(), Toast.LENGTH_SHORT).show();
}
});
*/
}
#Override
public void onClick(View v) {
//another activity to fill another listView
if (v.getId() == R.id.btn_save_participants_selected) {
ArrayList<Participants> selectedListData = new ArrayList<>();
if (listData != null && listData.size() > 0) {
for (int i = 0; i < listData.size(); i++) {
if (listData.get(i).isSelected()) {
selectedListData.add(listData.get(i));
}
}
//Pass this selectedListData to new activity to show a new Listview
}
}
}
}
Your adapter code change for selection and deselection.
public ParticipantsSelectedListAdapter(Context context, int a, ArrayList<Participants> participants) {
super(context, 0, participants);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
final Participants participants = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_participants_selected, parent, false);
}
// Lookup view for data population
TextView tvFirstName = (TextView) convertView.findViewById(R.id.tvFirstName);
TextView tvPosition = (TextView) convertView.findViewById(R.id.tvPosition);
CheckBox ckb = (CheckBox) convertView.findViewById(R.id.ckb);
// Populate the data into the template view using the data object
tvFirstName.setText(participants.getFirstName());
tvPosition.setText(participants.getPosition());
if(participants.isSelected) {
ckb.setChecked(true);
}else {
ckb.setChecked(false);
}
ckb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
participants.setSelected(!participants.isSelected());
notifyDataSetChanged();
}
});
// Return the completed view to render on screen
return convertView;
}
I have a list in which i can assigned the values statically.
private List<ListData> mDataList = Arrays.asList(
new ListData("Arun"),
new ListData("Jega"),
new ListData("Kabilan"),
new ListData("Karthick"),
new ListData("Joushva"),
new ListData("Niranjana"),
new ListData("Paramesh"),
new ListData("Prabha"),new ListData("Test1"),new ListData("Test2") );
The problem is now i got a scenario where i should get these value dynamically from web apim and i have to set it to the List variable mDataList.
Please help me to clear this. Thanks in advance.
Here is my complete code.
public class ReportFragment extends Fragment {
View ParentView;
private static final int HIGHLIGHT_COLOR = 0x999be6ff;
// list of data items
private List<ListData> mDataList = Arrays.asList(
new ListData("Arun"),
new ListData("Jega"),
new ListData("Kabilan"),
new ListData("Karthick"),
new ListData("Joushva"),
new ListData("Niranjana"),
new ListData("Paramesh"),
new ListData("Prabha"),new ListData("Test1"),new ListData("Test2")
);
// declare the color generator and drawable builder
private ColorGenerator mColorGenerator = ColorGenerator.MATERIAL;
private TextDrawable.IBuilder mDrawableBuilder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ParentView= inflater.inflate(R.layout.report_fragment, container, false);
init();
return ParentView;
}
public void init(){
mDrawableBuilder = TextDrawable.builder()
.round();
// init the list view and its adapter
final ListView listView = (ListView) ParentView.findViewById(R.id.listView1);
listView.setAdapter(new SampleAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
private class SampleAdapter extends BaseAdapter {
#Override
public int getCount() {
return mDataList.size();
}
#Override
public ListData getItem(int position) {
return mDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(getActivity() , R.layout.list_item_layout, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListData item = getItem(position);
// provide support for selected state
updateCheckedState(holder, item);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// when the image is clicked, update the selected state
ListData data = getItem(position);
data.setChecked(!data.isChecked);
updateCheckedState(holder, data);
}
});
holder.textView.setText(item.data);
return convertView;
}
private void updateCheckedState(ViewHolder holder, ListData item) {
if (item.isChecked) {
holder.imageView.setImageDrawable(mDrawableBuilder.build(" ", 0xff616161));
holder.view.setBackgroundColor(HIGHLIGHT_COLOR);
holder.checkIcon.setVisibility(View.VISIBLE);
}
else {
TextDrawable drawable = mDrawableBuilder.build(String.valueOf(item.data.charAt(0)), mColorGenerator.getColor(item.data));
holder.imageView.setImageDrawable(drawable);
holder.view.setBackgroundColor(Color.TRANSPARENT);
holder.checkIcon.setVisibility(View.GONE);
}
}
}
private static class ViewHolder {
private View view;
private ImageView imageView;
private TextView textView;
private ImageView checkIcon;
private ViewHolder(View view) {
this.view = view;
imageView = (ImageView) view.findViewById(R.id.imageView);
textView = (TextView) view.findViewById(R.id.textView);
checkIcon = (ImageView) view.findViewById(R.id.check_icon);
}
}
private static class ListData {
private String data;
private boolean isChecked;
public ListData(String data) {
this.data = data;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
}
}
create a method to add items in your adapter class, this method will add item to
itemlist. this will add items dynamically on your list or grid.
e.g
public void addItem(Item item){
itemList.add(item);
notifydatasetchanged();}
create a adapter class and constructor, in constructor just initialize the item arraylist and create extra method called addItem() this method will add item to your arraylist. after that you just have to call notifyDatasetchanged and your new item will be added.
I'm trying to get the onclick event of a button inside a listview, but it's not working
fragment_contact.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="404dp"
android:layout_weight="0.64"
android:orientation="horizontal"
android:paddingBottom="40dip" >
<ListView
android:id="#+id/contactlistview"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="fill"
android:layout_weight="10"
android:textSize="5pt"
android:visibility="visible" />
</LinearLayout>
fragment_contact_content.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btn_edit_contact"
android:layout_gravity="right" />
</LinearLayout>
FragmentContact.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_contact, container, false);
ListAdapter adapter_contact = new SimpleAdapter(
getActivity(), allcontact,
R.layout.fragment_contact_content, new String[]{"name", "level", "function", "phone", "email"},
new int[]{R.id.contact, R.id.level, R.id.function, R.id.phone, R.id.email});
listview_contact = (ListView) view.findViewById(R.id.contactlistview);
listview_contact.setItemsCanFocus(true);
listview_contact.setAdapter(adapter_contact);
Button btn_edit_contact = (Button) view.findViewById(R.id.btn_edit_contact);
btn_edit_contact.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Do something");
}
});
return view;
}
I also tried inflating fragment_contact_content.xml but the button still does nothing.
Use custom Adapter and in getView Write your code
public class MealAdapter extends BaseAdapter{
private int mHour, mMinute;
int minutes,hour;
String strtime;
customButtonListener customListner;
private Context context;
private List<Meal> rowItems;
public MealAdapter(Context context, List<Meal> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
private class OptionHolder
{
ImageButton btn_time;
ImageButton btn_delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final OptionHolder holder;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.meal_list_item, null);
holder = new OptionHolder();
holder.btn_time= (ImageButton) convertView.findViewById(R.id.btn_time);
holder.btn_delete =(ImageButton) convertView.findViewById(R.id.btn_delete_meal);
convertView.setTag(holder);
}
else
{
holder = (OptionHolder) convertView.getTag();
}
final Meal row_pos=rowItems.get(position);
row_pos.setMeal("");
row_pos.setDetail("");
holder.ed_meal.setText(row_pos.getMeal());
holder.ed_detail.setText(row_pos.getDetail());
holder.ed_time.setText(row_pos.getTime());
holder.btn_time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(MealPlannerFragment.con,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
strtime=(hourOfDay + ":" + minute);
row_pos.setTime(strtime);
row_pos.setMunite(minute);
row_pos.setHour(hourOfDay);
holder.ed_time.setText(row_pos.getTime());
}
}, mHour, mMinute, false);
tpd.show();
}
});
holder.btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (customListner != null) {
customListner.onButtonClickListner(position,row_pos);
}
}
});
return convertView;
}
public interface customButtonListener {
public void onButtonClickListner(int position,Meal row_pos);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
}
`
you can not get Listview cell's Button event directly in onCreateView. you have to make CustomAdapter class for that.
you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fragment_contact_content, null);
}
//Handle button and add onClickListener
Button editBtn = (Button)view.findViewById(R.id.btn_edit_contact);
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
//some other task
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
You can refer this link: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
just handle on click listener inside getview where you find the button using findviewbyid
I hope it helps!
I am trying to create a custom listview like this: http://i.stack.imgur.com/l8ZOc.png
Currently I managed to create it but there is a problem. For example when there are 8 items, it loads the first 4, then loads the remiaining items as you scroll down. When scrolling down, it works fine.
However, when scrolling back up from bottom, at the middle of list, it instantly moves to top, skipping 2-3-4. items. Then you can scroll down normally again, but when scrolling up, it instantly goes to top of the list.
How can i prevent this from happening?
Here is my code:
public class MyActivity extends Activity implements AdapterView.OnItemClickListener {
String headers[];
String image_urls[];
List<MyMenuItem> menuItems;
ListView mylistview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
menuItems = new ArrayList<MyMenuItem>();
headers = getResources().getStringArray(R.array.header_names);
image_urls = getResources().getStringArray(R.array.image_urls);
for (int i = 0; i < headers.length; i++) {
MyMenuItem item = new MyMenuItem(headers[i], image_urls[i]);
menuItems.add(item);
}
mylistview = (ListView) findViewById(R.id.list);
MenuAdapter adapter = new MenuAdapter(this, menuItems);
mylistview.setAdapter(adapter);
mylistview.setOnItemClickListener(this);
}
}
public class MyMenuItem {
private String item_header;
private String item_image_url;
public MyMenuItem(String item_header, String item_image_url){
this.item_header=item_header;
this.item_image_url=item_image_url;
}
public String getItem_header(){
return item_header;
}
public void setItem_header(String item_header){
this.item_header=item_header;
}
public String getItem_image_url(){
return item_image_url;
}
public void setItem_image_url(String item_image_url){
this.item_image_url=item_image_url;
}
}
public class MenuAdapter extends BaseAdapter{
Context context;
List<MyMenuItem> menuItems;
MenuAdapter(Context context, List<MyMenuItem> menuItems) {
this.context = context;
this.menuItems = menuItems;
}
#Override
public int getCount() {
return menuItems.size();
}
#Override
public Object getItem(int position) {
return menuItems.get(position);
}
#Override
public long getItemId(int position) {
return menuItems.indexOf(getItem(position));
}
private class ViewHolder {
ImageView ivMenu;
TextView tvMenuHeader;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_item, null);
holder = new ViewHolder();
holder.tvMenuHeader = (TextView) convertView.findViewById(R.id.tvMenuHeader);
holder.ivMenu = (ImageView) convertView.findViewById(R.id.ivMenuItem);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
MyMenuItem row_pos = menuItems.get(position);
Picasso.with(context)
.load(row_pos.getItem_image_url())
// .placeholder(R.drawable.empty)
// .error(R.drawable.error)
.into(holder.ivMenu);
holder.tvMenuHeader.setText(row_pos.getItem_header());
Log.e("Test", "headers:" + row_pos.getItem_header());
return convertView;
}
}
<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"
tools:context=".MyActivity">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
Use lazy loading mechanism to load your image data.
There is one nice example here
I have made an Listview populated with list_row_layout.xml(which is populated with json serializable class), i have clickable textview and onclick changing text from "Accept" to "Accepted". But when i click it on first listview item, another textview listview items below are changing. Here's some photos to descibe you better
Activity class
feedListView.setAdapter(new CustomListAdapter(this, feedList));
adapter class
public class CustomListAdapter extends BaseAdapter
{
private ArrayList<FeedItem> listData;
private LayoutInflater layoutInflater;
private Context mContext;
public CustomListAdapter(Context context, ArrayList<FeedItem> listData)
{
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
mContext = context;
}
#Override
public int getCount()
{
return listData.size();
}
#Override
public Object getItem(int position)
{
return listData.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if (convertView == null)
{
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.headlineView = (TextView)convertView.findViewById(R.id.title);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.confid);
holder.approve = (TextView) convertView.findViewById(R.id.approveTV);
holder.approve.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View argView)
{
holder.approve.setText("accepted");
}
}
);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = listData.get(position);
holder.headlineView.setText(Html.fromHtml(newsItem.getTitle()));
holder.reportedDateView.setText(Html.fromHtml(newsItem.getContent()));
holder.approve.setTag(newsItem);
return convertView;
}
static class ViewHolder
{
TextView approve;
TextView headlineView;
TextView reportedDateView;
ImageView imageView;
}
}
textview code
<TextView
android:id="#id/approveTV"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginRight="5dp"
android:background="#drawable/pressed"
android:gravity="fill"
android:text="Accept"
android:clickable="true"
android:textColor="#0D98BA"
android:textSize="17sp" />
You have to write some tracking position functionality which remember the position which you have changed and make sure that only text of position changed .
you must set id to each row, and save it in one array,like integer and when you click on one row you must change the value of that, and in changing text or anything you must check the value of that row,if 0 then set default and if 1 then so what you want: my idea is create int[] with length of that is size of your list,
first you must define you int[] like below and set to zero every index.
int[] selected = new int[listData.getsize()]
something like this in getview:
holder.approve.setId(Html.fromHtml(newsItem.getId());
and after else statement in getView:
if (selected[position] == 0)
{
// set default
}
else
{
// any changing that you want
}
and in onClick:
selected[holder.approve.getId()] = 1;
// any change that you want
Try the below code:-
public View getView(final int position, View convertView, ViewGroup parent)
{
final ViewHolder holder;
if (convertView == null)
{
holder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder.headlineView = (TextView)convertView.findViewById(R.id.title);
holder.reportedDateView = (TextView) convertView.findViewById(R.id.confid);
holder.approve = (TextView) convertView.findViewById(R.id.approveTV);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
FeedItem newsItem = listData.get(position);
holder.headlineView.setText(Html.fromHtml(newsItem.getTitle()));
holder.reportedDateView.setText(Html.fromHtml(newsItem.getContent()));
holder.approve.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View argView)
{
holder.approve.setText("accepted");
}
}
);
return convertView;
}
Thanks!!