Android Listview - Change Item Button Text After Clicking - android

I am trying to convert my app to android version, and I am a bit new in android. I have a list view in which the items include buttons. It is a user list and you can follow each user, when the button is clicked, only in the item including the button, the button text should turn in to "followed". Retrieving the list works fine, but with my below code the button text is not changing. How can I make this happen? Thank you very much.
private class MyListAdapter extends ArrayAdapter<String> {
public MyListAdapter() {
super(getActivity().getApplicationContext(), R.layout.fragment_users_cell, myItemList);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View cellView = convertView;
if (cellView == null){
cellView = getActivity().getLayoutInflater().inflate(R.layout.fragment_users_cell, parent, false);
}
profileBtn = (Button) cellView.findViewById(R.id.fragment_users_cell_profileBtn);
followBtn = (Button) cellView.findViewById(R.id.fragment_users_cell_followBtn);
profileBtn.setText(myItemList.get(position));
profileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(myItemList.get(position));
System.out.println(position);
}
});
followBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println(myItemList.get(position));
profileBtn.setText("followed");
}
});
return cellView;
}
}

You have to update your dataset and refersh the list after you make changes so that it reflects the latest changes. In your case the text changes.
followBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
profileBtn.setText("followed");
myItemList.add(position, "followed");//Change your dataset
notifyDataSetChanged(); //And refresh the adapter
}
});

you need to change the value in myItemList so that next time when view load, the value from list set as text on profile button comes which ix followed
i.e. you need to update the list on click of follow button and notify the ListView.
followBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
System.out.println(myItemList.get(position));
myItemList.get(position).set("followed");
profileBtn.setText("followed");
}
});

Related

Button on ListAdapter

I have button on items in my list adapter. The problem occurs when I click the button. The action is performed on the right item, but it disables wrong button.
My code:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater =
(LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_friend, parent, false);
user = userList.get(position);
ImageView imageView = (ImageView)view.findViewById(R.id.user_image);
Picasso.with(JSONUserAdapter.this.getContext()).load("https://s3.amazonaws.com/profiles-pictures/"+ user.getPath()).into(imageView);
sendRequest = (ImageButton)view.findViewById(R.id.sendRequest);
sendRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendFriendRequest();
disabledAdd();
}
});
return view;
}
Do not try to catch click events for the buttons inside the rows of ListView. Each row of ListView is already clickable. Set the onItemClickListener for the ListView:
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long l) {
//DO SOMETHING HERE
//Use "position" to get the index of item clicked
}
});
As i can see that we had defined the "User" object as a globel variable and it will store the last postions item data.
So when you will click on any button the last items data will be reflected.
{UserType}Object user = userList.get(position);
You can set Tag on View
Use like this:
sendRequest.setTag(user);
And When user clicks item let's get data from tag like this
sendRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Here you have user that was clicked.
User user = v.getTag();
sendFriendRequest();
disabledAdd();
}
});

Listview is not getting updated immediately after button click

I have a list view that contains Product (productid, productname) + one button
I am filling ArrayList below.
ArrayList<Product> products = new ArrayList<Product>();
//fill products here
productAdapter adapter = new ProductAdapter(getApplicationContext(), products);
productListView.setAdapter(adapter);
productListView.setVisibility(View.VISIBLE);
Now in adapter
public View getView(final int position, View convertView, ViewGroup parent) {
// some other code
holder.btn_addtocart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
products.get(position).setname("ABC");
}
});
}
Problem is its not updating immediately. When we scroll down and up its getting changed.
Why is not not updating listview immediately?
How to fix this?
To refresh the list, you need to call notifyDataSetChanged() after updating the data.
eg:
holder.btn_addtocart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
products.get(position).setname("ABC");
notifyDataSetChanged();
}
});

Having problems while trying to delete single rows from a custom ToDo list?

I want to delete selected rows from a todo list by clicking on the checkbox and deleting them trough the delete button, for that I am within my custom adapter setting a setOnCheckedChangeListener on my checkbox and setOnClickListener on my delete button, now keep in mind that the delete button is inflated on my fragment view and I am using it on my row view, but the problem is only the last element from my todo list is getting deleted not the rest of them, I tried working within the fragment view and notify the adapter later on but all I got was a null pointer error on my checkbox.
Row View:
todoCheckBox = (CheckBox) convertView.findViewById(R.id.todo_CheckBox);
todoTextView.setText(values.get(position));
todoCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Toast.makeText(getContext(), " CheckBox Status: " + isChecked, Toast.LENGTH_LONG).show();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mDelete.isPressed() && (todoCheckBox.isChecked())) {
//convertView.clearFocus(position);
mAdapter.clear();
//mAdapter.notifyDataSetChanged();
}
}
});
}
});
Fragment View:
#TargetApi(9) // remember this for isEmpty()
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_todo, container, false);
ArrayList<String> todoList = new ArrayList<String>();
mAdapter = new UsersAdapter(getActivity(), todoList);
listViewToDo = (ListView) v.findViewById (android.R.id.list);
listViewToDo.setAdapter(mAdapter);
mToDoField = (EditText) v.findViewById(R.id.todo_editText);
mDelete = (Button) v.findViewById(R.id.delete_button);
mAdd = (Button)v.findViewById(R.id.add_button);
mAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String toDo = mToDoField.getText().toString().trim();
if (toDo.isEmpty()){
return;
}
mAdapter.add(toDo);
mToDoField.setText("");
}
});
return v;
}
}
You need to assign an onclick listener to your delete button outside of the onChecked statement. Add it in code just after you assign the onClick event to the add button. This is because a view in android can only have 1 listener per event type.
The onClick event can look something like below using a sparese
mDelete.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
SparseBooleanArray checked = listViewToDo.getCheckedItemPositions();
for (int i = 0; i < listViewToDo.getCount(); i++){
if (checked.get(i)==true)
{
mAdapter.remove(i);
}
mAdapter.notifyDataSetChanged();
}
listViewToDo.clearChoices();
}
});

set Text into TextViews in ListView from Dialog in Android

I have a ListView dynamically inflated with custom layout that has different text views and a button. On button click, a user specifies options in a dialog window and the data returned to the selected item in the list view.
I expect the data to get inserted in text views of the corresponding item in the list view. However, when the list has fewer item that are not scrollable, no data gets inserted at all when dialog is closed and when it has enough items to be scrollable, the data gets inserted into text views of wrong item in the list. I don't know what I am doing wrong, here is my code:
public double COST_EM = 0.00, COST = 0.00, NUM_CO = 0.00;
private Spinner mPSpinner, mMediSpinner;
private ArrayAdapter<String> pmedi, numCo;
private TextView mPTv, mCoTv, mSubMain, mSubTv;
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
View view = null;
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.item_custom_layout, parent, false);
// Display image in the ImageView widget
TempP tphoto = tempPList.get(position);
mPTv = (TextView) view.findViewById(R.id.p_tv_po);
mCoTv = (TextView) view.findViewById(R.id.co_tv_po);
mSubMain = (TextView) view.findViewById(R.id.sub_list);
mModify = (Button) view.findViewById(R.id.modify_btn_po);
mModify.setOnClickListener(new View.OnClickListener() {
// calculate the order cost
protected void calculateCost() {
mSub = ((COST_EM + COST) * NUM_CO);
mSubtv.setText("" + Double.toString(mSub));
}
#Override
public void onClick(View v) {
mDialog = new Dialog(PCustom.this);
mDialog.setContentView(R.layout.item_custom_dialog);
mDialog.setTitle("Modify specifications");
mPSpinner = (Spinner) mDialog.findViewById(R.id.ces_sp_dialog);
mSubTv = (TextView) mDialog.findViewById(R.id.sub_der_dialog);
// set spinner adapters (code truncated for brevity)
pmedi = new ArrayAdapter<String>(MyApplication
.getContext(), R.layout.spinner_style, pmedi);
mPSpinner.setAdapter(pmedi);
mPSpinner
.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0,
View arg1, int pos, long arg3) {
if (mPSpinner.getSelectedItem() == "Glossy") {
COST = 2000.00;
} else if (mPSpinner
.getSelectedItem() == "Standard") {
COST = 1500.00;
} else if (mPSpinner
.getSelectedItem() == "Other") {
COST = 1000.00;
}
// calculate the cost
calculateCost();
}
public void onNothingSelected(
AdapterView<?> arg0) {
}
});
Button save = (Button) mDialog
.findViewById(R.id.save_btn_po_dialog);
Button cancel = (Button) mDialog
.findViewById(R.id.cancel_btn_po_dialog);
save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// String newnumber =
// mobileNumber.getText().toString();
mPTv.setText("" + mPSpinner
.getSelectedItem());
mCoTv.setText((String) mNCoSpinner
.getSelectedItem());
mSubMain.setText(Double.toString(mSub));
mDialog.dismiss();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDialog.dismiss();
}
});
mDialog.show();
}
});
return view;
}
The method getView() return one item View each time ListView call it with a specific "position" parameter, so the times it is called is no less than the number of items it has. So, your member variables mPTv, mCoTv and mSubMain will be reassigned many times and finally have their values in the final calling of getView().That's why you meet that problem.
To solve your problem, you need to have the correct TextViews when the "save Button" is clicked.Here is how to find those correct TextViews:
In the OnClickListener of mModify Button, the "v" parameter in the method onClick(View v) is the same instance of mModify itself. So, you can use it to find those correct TextViews. Perhaps you can set the item root View as its tag and get the root View in onClick(View v) and then use it to find all those correct TextViews. Here is how to change your code:
mModify = (Button) view.findViewById(R.id.modify_btn_po);
// set the root view as the tag of "modify button".
mModify.setTag(view);
mModify.setOnClickListener(new View.OnClickListener() {
// calculate the order cost
protected void calculateCost() {
mSub = ((COST_EM + COST) * NUM_CO);
mSubtv.setText("" + Double.toString(mSub));
}
#Override
public void onClick(View v) {
// retrieve the root view here, it's the root view of the item on which you
// clicked the "modify button".
View view = (View)v.getTag();
// find the correct TextViews here.
mPTv = (TextView) view.findViewById(R.id.p_tv_po);
mCoTv = (TextView) view.findViewById(R.id.co_tv_po);
mSubMain = (TextView) view.findViewById(R.id.sub_list);
BTW, you didn't optimize your ListView, so it may not scroll smoothly, but this is not what caused your problem.You can refer to this:
How to optimize Android ListView?

Highlight selected Spinner Item

I have implemented Custom Spinner using Button following wildnove's answer. Everything works fine, but I am not able to display the highlighted radio button for the selected button.
Below is the code.
((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// How to highlight Radio button of a selected Item???
final String[] items = view.getResources().getStringArray(R.array.planets__entries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
((Button) findViewById(R.id.btnSpinnerPlanets)).setText(items[which]);
dialog.dismiss();
}
}).create().show();
}
});
Can somebody help me how to highlight selected Item's Radio button ...
Unfortunately this behavior is not natively implemented in Spinner component, however, you can always create your own BaseAdapter to show whatever you need weather is in the spinner it self or in the dropdown like this:
private class ExampleAdapter extends BaseAdapter{
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Here is where you actually get the chance to return whatever you want in the spinner component (the single bar with the arrow)
return yourCommonView;
}
#Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
//Here is where you get the chance to return whatever you want in the dropdown menu so here you should validate what's the currently selected element and return an image accordingly...
return yourSelectedView;
}
}
The important method here is, getDropDownView that is the one that gives you the chance to return an element with a checked CheckBox, or any mark you want to use, of course you have to create your own layout and validate if the element currently created need to be marked or not...
Regards!
The problem with this code is that you are creating the Spinner each time the Button is clicked. Try the following code:
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
switch(id) {
case 1:
Button b=((Button) findViewById(R.id.btnSpinnerPlanets));
builder = new AlertDialog.Builder(MyFormActivity.this).setTitle("the prompt").setAdapter(get_the_adapter(b), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
b.setText(b.getResources().getStringArray(R.array.planets__entries)[which]);
dismissDialog(1);
}
})
dialog = builder.create();
break;
default:
dialog = null;
}
return dialog;
}
}
public ArrayAdapter<String> get_the_Adapter(Button view){
String[] items = view.getResources().getStringArray(R.array.planets__entries);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MyFormActivity.this, android.R.layout.simple_spinner_dropdown_item, items);
return adapter;
}
And for the Button's onClick():
((Button) findViewById(R.id.btnSpinnerPlanets)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog(1);
}
});

Categories

Resources