How do i determine the items populating listview? - android

im a noob to android and i am populating a listview with an arrayilst and custom adapter. I want setup my listview onClickListener to execute commands based to the the items populating the listview. the listview is dynamically populated with items from the arraylist. I have tried the position and id parameters with no luck. Any help is greatly appreciated.
How I instantiate listview, arraylist, and adapter
portfoliolist = (ListView) findViewById(R.id.listViewPortfolios);
users = new ArrayList<PortfolioRecord>();
portfoliolist.setAdapter(new UserItemAdapter(this, R.layout.simplerow, users));
portfoliolist.setOnItemClickListener(this);
My Custom Adapter.
public class UserItemAdapter extends ArrayAdapter<PortfolioRecord> {
private ArrayList<PortfolioRecord> users;
public UserItemAdapter(Context context, int textViewResourceId, ArrayList<PortfolioRecord> users) {
super(context, textViewResourceId, users);
this.users = users;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.simplerow, null);
}
PortfolioRecord user = users.get(position);
if (user != null) {
TextView portfolioname = (TextView) v.findViewById(R.id.portfolioname);
TextView currentvalue = (TextView) v.findViewById(R.id.currentvalue);
if (portfolioname != null) {
portfolioname.setText(user.portfolioname);
}
if(currentvalue != null) {
currentvalue.setText("Current Value: " + user.currentvalue );
}
}
return v;
}
}
public class PortfolioRecord {
public String portfolioname;
public String currentvalue;
public PortfolioRecord(String portfolioname, String currentvalue) {
this.portfolioname = portfolioname;
this.currentvalue = currentvalue;
}
}
How i add items to arraylist:
user1 = new PortfolioRecord(pn10, denomination10+portfoliovalue10);
users.add(user1);
I have added Usernull, user1 and user2 to my arraylist. How do i identify these items? I've tried the folowing code with no luck
public void onItemClick(AdapterView parent, View itemClicked, int position,
long id) {
TODO Auto-generated method stub
switch(parent.getId()){
case R.id.listViewPortfolios:
if(portfoliolist.getSelectedItem()==usernull){
openCustomDialog();
}else if(portfoliolist.getSelectedItem()==user1){
whichportfolio=1;
}else if(portfoliolist.getSelectedItem()==user2){
whichportfolio=2;
}
break;}}

No need to implement OnItemSelectedListener. Just use this within the existing OnItemClick method:
public void onItemClick(AdapterView parent, View itemClicked, int position,
long id) {
// TODO Auto-generated method stub
PortfolioRecord user = users.get(position);
// I'm not certain what this code block does...
if(user.equals(usernull)){
openCustomDialog();
}else if(user.equals(user1)){
whichportfolio=1;
}else if(user.equals(user2)){
whichportfolio=2;
}}

supposing your portfolioRecord object has the following: getTypeofUser()
portfoliolist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
String typeofUser =users.get(position).getTypeofUser();
if(typeofUser == user1 ){
whichportfolio=1;
}
}
});

I recommend changing to a OnItemSelectedListener and then you could simply fetch the PortfolioRecord with:
listView.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView parent, View view, int position, long id) {
// Get the user (PortfolioRecord) that was selected
PortfolioRecord user = users.get(position);
// I'm not certain what this code block does...
if(user.equals(usernull)){
openCustomDialog();
}else if(user.equals(user1)){
whichportfolio=1;
}else if(user.equals(user2)){
whichportfolio=2;
}
}
});

Related

Expandable List view child item selection in android?

In expandable list view set the data based on the parent. In this parent has child item selection, the selection set image view for each child item selection. But in this selection set the other parents child items.
Below code for parent value set.
#Override
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
GroupViewHolder groupViewHolder;
if(view==null){
groupViewHolder=new GroupViewHolder();
view=((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.category_listview_group_item,null);
groupViewHolder.name=(TextView)view.findViewById(R.id.category_listview_item_name);
groupViewHolder.nameIcon=(ImageView)view.findViewById(R.id.category_listview_item_icon);
groupViewHolder.progressBar = (ProgressBar)view.findViewById(R.id.categoryImageProgressBarlist);
groupViewHolder.rigtharrow=(ImageButton)view.findViewById(R.id.category_listview_item_onclick);
view.setTag(groupViewHolder);
} else {
groupViewHolder=(GroupViewHolder)view.getTag();
}
groupViewHolder.nameIcon =itemImage(view, R.id.category_listview_item_icon, data.get(i).getImageUrl(), groupViewHolder.progressBar);
groupViewHolder.name.setText(data.get(i).getName());
return view;
}
Below code for child item value set
#Override
public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
final ChildViewHolder childViewHolder;
String[] spinnerCount = {"1","2","3","4","5"};
if(view==null) {
childViewHolder = new ChildViewHolder();
view = ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.category_listview_child_item,null);
childViewHolder.childName = (TextView)view.findViewById(R.id.listview_child_item_name);
childViewHolder.childNamePrice = (TextView)view.findViewById(R.id.listview_child_item_price);
childViewHolder.childNameIcon = (ImageView)view.findViewById(R.id.listview_child_item_icon);
childViewHolder.spinner = (Spinner)view.findViewById(R.id.spinner);
view.setTag(childViewHolder);
}
else {
childViewHolder=(ChildViewHolder)view.getTag();
}
childViewHolder.childNameIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!childViewHolder.childNameIcon.isSelected()) {
childViewHolder.childNameIcon.setBackgroundResource(R.mipmap.yellow_circle_list_item);
childViewHolder.childNameIcon.setSelected(true);
// childViewHolder.childNameIcon.setTag(R.mipmap.yellow_circle_list_item);
String quantity = childViewHolder.spinner.getSelectedItem().toString();
Products product = data.get(i).getProductsList().get(i1);
product.setQuantity(quantity);
dataHandler.addTempproducts(product);
} else {
childViewHolder.childNameIcon.setBackgroundResource(R.mipmap.black_circle_list_item);
childViewHolder.childNameIcon.setSelected(false);
// childViewHolder.childNameIcon.setTag(R.mipmap.black_circle_list_item);
dataHandler.removeTempProducts(data.get(i).getProductsList().get(i1));
Products product = data.get(i).getProductsList().get(i1);
product.setQuantity("1");
}
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,android.R.layout.simple_spinner_item,spinnerCount);
childViewHolder.spinner.setAdapter(adapter);
childViewHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String spinnerCount = childViewHolder.spinner.getSelectedItem().toString();
Products product = data.get(i).getProductsList().get(i1);
ArrayList<Products> productList = new ArrayList<Products>();
productList = dataHandler.getTempproducts();
if (childViewHolder.childNameIcon.isSelected()) {
for (int k = 0; k < productList.size(); k++) {
if (data.get(i).getProductsList().get(i1).getId() == productList.get(k).getId()) {
productList.get(k).setQuantity(spinnerCount);
}
}
} else {
product.setQuantity(spinnerCount);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
childViewHolder.childName.setText(data.get(i).getProductsList().get(i1).getName());
if(data.get(i).getProductsList().get(i1).getPrice().isEmpty()) {
childViewHolder.childNamePrice.setText(data.get(i).getProductsList().get(i1).getPrice());
} else {
childViewHolder.childNamePrice.setText(data.get(i).getProductsList().get(i1).getPrice()+"/-");
}
return view;
}
Please Help me , i am struct here.......

Fragment ListView Inflation of new Row to Maintain onItemClick Selection

I have a ListView that is within a Fragment. In the onCreateView section I have set a onItemClickListener for the list, which highlights the selected item in the ListView. I have set two ImageButtons that navigate up and down the list. On selection a new Row is inflated that has its TextView's set to the content of the select item (for the purpose of retaining the highlighted selected state). However I am having difficulty adding that item back to the list. The app will not compile due to the line routines.add(selectedPos-1, str); it wants wants int location, Routine object. I believe the issue is with my construction of my SelectedAdapter class, but I have been unable to determine what to change/pass with regard to the Object.
IE:
public SelectedAdapter(Context context, int textViewResourceId,List objects) {
super(getActivity(), R.layout.listview_routines, routines); }
I would greatly appreciate any input as how to correct this issue; as well as any advice if there is a better way to maintain a selected state. Thanks for your help.
Fragment:
public static class FragmentRoutine extends Fragment {
DatabaseHandler db;
private ListView routineListView;
private List<Routine> routines = new ArrayList<Routine>();
ArrayAdapter<Routine> routineAdapter;
Routine longClickedItemRoutines;
private SelectedAdapter selectedAdapter;
public FragmentRoutine() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.routines,
container, false);
db = new DatabaseHandler(getActivity().getApplicationContext());
routineListView = (ListView) rootView.findViewById(R.id.routineList);
registerForContextMenu(routineListView);
db.closeDB();
if (db.getExerciseCount() != 0)
routines.clear();
routines.addAll(db.getAllRoutines());
populateList();
selectedAdapter = new SelectedAdapter(this.getActivity(), 0, routines);
selectedAdapter.setNotifyOnChange(true);
routineListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemRoutines = routines.get(position);
return false;
}
});
routineListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView arg0, View view,
int position, long id) {
selectedAdapter.setSelectedPosition(position);
}
});
routineListView.post(new Runnable() {
#Override
public void run() {
routineListView.setItemChecked(0, true);
}
});
// move up event handler
ImageButton btnMoveUp = (ImageButton) rootView.findViewById(R.id.btnMoveUp);
btnMoveUp.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveUp();
}
});
// move down event handler
ImageButton btnMoveDown = (ImageButton) rootView.findViewById(R.id.btnMoveDown);
btnMoveDown.setOnClickListener(new AdapterView.OnClickListener() {
public void onClick(View arg0) {
moveDown();
}
});
setHasOptionsMenu(true);
return rootView;
}
// Move selected item "up" in the ViewList.
private void moveUp(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos > 0 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
//Problem Line Below
routines.add(selectedPos-1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos-1);
}
}
// Move selected item "down" in the ViewList.
private void moveDown(){
Routine currentToDoSave = routines.get(selectedAdapter.getSelectedPosition());
int selectedPos = selectedAdapter.getSelectedPosition();
if (selectedPos < routines.size()-1 ){
routines.remove(selectedPos);
String str = currentToDoSave.getTagName();
routines.add(selectedPos+1, str);
// set selected position in the adapter
selectedAdapter.setSelectedPosition(selectedPos+1);
}
}
public class SelectedAdapter extends ArrayAdapter<Routine>{
// used to keep selected position in ListView
private int selectedPos = -1; // init value for not-selected
public SelectedAdapter(Context context, int textViewResourceId,
List objects) {
super(getActivity(), R.layout.listview_routines, routines);
}
public void setSelectedPosition(int pos){
selectedPos = pos;
// inform the view of this change
notifyDataSetChanged();
}
public int getSelectedPosition(){
return selectedPos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
// only inflate the view if it's null
if (v == null) {
LayoutInflater vi
= (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.selected_row, null);
}
// get text view
TextView label = (TextView)v.findViewById(R.id.txtExample);
// change the row color based on selected state
if(selectedPos == position){
label.setBackgroundColor(Color.CYAN);
}else{
label.setBackgroundColor(Color.WHITE);
}
label.setText(this.getItem(position).toString());
return(v);
}
}
private void populateList() {
routineAdapter = new SaveListAdapterT();
routineListView.setAdapter(routineAdapter);
}
public class SaveListAdapterT extends ArrayAdapter<Routine> {
public SaveListAdapterT() {
super(getActivity(), R.layout.listview_routines, routines);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null)
view = getActivity().getLayoutInflater().inflate(R.layout.listview_routines, parent, false);
Routine currentToDoSave = routines.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(currentToDoSave.getTagName());
return view;
}
}
}

Android Java: Unable to selectively highlight rows in a ListView via onScroll listener

I have another blocker as I study Android Development.
This time my problem is when I wanted to "selectively" highlight a row in a ListView populated by data from an adapter.
This ListView is actually within a dialog, and purpose is to show a list of friends, where user can multi-select and highlight it as he selects.
The selected values by the way, is stored in an ArrayList "arr_FriendsShare" so that the next time he opens the listview, rows will be highlighted (via onScrollListener) for those previously selected.
What is currently happening, only the "recently" or "last" clicked row/item is highlighted; and seems to be clearing all the previously highlighted rows.
I cannot understand why it is behaving that way, as row's value is successfully stored to/removed from arr_FriendsShare ArrayList, as I click on it.
Below is my listener codes, and thanks in advance for the usual help:
//Item click listener for Select Friends ListView
listview_SelectFriends.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String friends_ListItemSelected = (String)adapter.getItemAtPosition(position);
if(!arr_FriendsShare.contains(friends_ListItemSelected)){
arr_FriendsShare.add(friends_ListItemSelected);
}
else{
removeItemFromArrayListString(Main.this, arr_FriendsShare, friends_ListItemSelected);
}
}
});
listview_SelectFriends.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
for (int i = firstVisibleItem; i < (visibleItemCount + firstVisibleItem); i++) {
String listViewItemText = view.getItemAtPosition(i).toString();
if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(getResources().getColor(R.color.red_light));
view.setSelector(cd);
}
else if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(Color.TRANSPARENT);
view.setSelector(cd);
}
}
}
});
Additional Code Block:
ArrayList<String> stringArray = new ArrayList<String>();
String jsonURL = <SOME URL HERE>;
stringArray = Global.getStringArrayFromJSON(Main.this, jsonURL, "friends", "FriendUsername");
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.friends_list_layout, null);
ListView listview_SelectFriends = (ListView) convertView.findViewById(R.id.layout_Friends);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
listview_SelectFriends.setAdapter(adapter);
Change
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
to
// Define this at class level as --> private FriendsAdapter adapter = null;
adapter = new FriendsAdapter(Main.this, stringArray);
add this method in your activity
private void setResetSelection(int index, boolean setSelection){
View v = listview_SelectFriends.getChildAt(index);
if(v != null){
TextView name = (TextView) v.findViewById(R.id.name);
if(setSelection)
name.setBackgroundResource(R.color.red);
else
name.setBackgroundResource(R.color.transparent);
}
}
and create a new class as
public class FriendsAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> mFriends;
private ArrayList<String> mSelectedFriends = new ArrayList<String>();
public GoodPeopleAdapter(Context context, ArrayList<String> friends) {
mInflater = LayoutInflater.from(context);
mFriends= friends;
}
public void setSelectedFriends(ArrayList<String> selectedFriends){
mSelectedFriends = selectedFriends;
}
#Override
public int getCount() {
return mFriends.size();
}
#Override
public Object getItem(int position) {
return mFriends.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if(convertView == null) {
view = mInflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.name = (TextView)view.findViewById(R.id.name);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
String name = mFriends.get(position);
holder.name.setText(name);
if(mSelectedFriends.contains(name))
holder.name.setBackgroundResource(R.color.red) // red is in color xml by default, change according to your choice
return view;
}
private class ViewHolder {
public TextView name;
}
}
Add following line at the end of method onItemClick
adapter.setSelectedFriends(arr_FriendsShare);
Add this in the if part of onItemClick
setResetSelection(position, true);
and this in else part
setResetSelection(position, false);
Also create a new xml layout with name row_layout with a textview with id name.

Update Listview item and get values using BaseAdapter Android

I have a listview of that have multiple items.I want to update the items value on click of button and want to get the the values of all the items on click of the button.But i am unable to do that.Please help me to get this functionality
Activity code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_ItemValue);
setContentView(R.layout.activity_iween_booking_page);
listView = (ListView) findViewById(R.id.passengerList);
showPassengerListView(passengerList);
}
getValue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if(){
}else{
//Here i have to get all the value of the listview items in a array
}
}
});
}
private void showPassengerListView(final String[] passengerList) {
listView.setAdapter(new PassengerListUpdate(passengerList));
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
public void passengerInformationPopup(final String[] passengerList, final int position) {
final Dialog dialog= new Dialog(MainActivity.this,R.style.Dialog_Fullscreen);
dialog.setContentView(R.layout.passenger_details_dialog);
dialog.show();
setValueDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
isSuccess= true;
if(isSuccess){
dialog.cancel();
//Here i Have to Update the item at position with some value
}
}
});
}
public void goBack(View v) {
finish();
}
class PassengerListUpdate extends BaseAdapter {
String[] ItemValue;
public PassengerListUpdate(String[] text) {
ItemValue = text;
}
public int getCount() {
// TODO Auto-generated method stub
return ItemValue.length;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View vi;
vi = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
TextView ItemValue;
ItemValue = (TextView) vi.findViewById(android.R.id.text1);
ItemValue.setText(ItemValue[position]);
return (vi);
}
}
Please help me to how to set a items value and how to get the listview values
[Want] to get the the values of all the items on click of the button
To get all values, create a method getAllValues() inside PassengerListUpdate:
public String[] getAllValues() {
return ItemValue;
}
Declare your adapter globally:
PassengerListUpdate myAdapter;
Initialize it in showPassengerListView(String[]):
myAdapter = new PassengerListUpdate(passengerList);
listView.setAdapter(myAdapter);
To get the list of all values on button click:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (myAdapter != null) {
String[] allValues = myAdapter.getAllValues();
}
}
});
I want to update the items value on click of button
To update the values, you can simply reinitialize and set myAdapter:
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myAdapter = new PassengerListUpdate(updatedPassengerList);
listView.setAdapter(myAdapter);
}
});
First, in order to get whole the values inside ListView. You can get number of item in adapter, and then get value one by one by its position.
ArrayList<String> results = new ArrayList<String>();
final int count = mMyAdapter.getCount();
for( int i = 0; i < count; ++i ){
String item = mMyAdapter.getItem(i);
results.add(item);
}
return results;
Second, in order to add or update the value of ListView, in general extending ArrayAdapter is much easier than implementing BaseAdapter, because of ArrayAdapter support add / remove / insert method by itself. For example,
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context) {
super(context, 0);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View vi;
vi = inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
TextView ItemValue;
ItemValue = (TextView) vi.findViewById(android.R.id.text1);
ItemValue.setText(ItemValue[position]);
return (vi);
}
}
And you can updating adapter's value quiet directly,
mMyAdapter.add("Add Item");
mMyAdapter.remove("Remove Item");
mMyAdapter.insert("Insert Item", 0);
After finishing the jobs, you can call adapter's notifyDatSetChanged() method in order to update the UI, and I think this is more efficient way than setting up the new adapter every time whenever data is updated.
mMyAdapter.notifyDataSetChanged();

ListView and List Adapter in android change color

I have a list activity which has a list showing results of a query. Well I want to be able to click on each item and the item changes color but it doesn't work. I want the item to remain selecetd state untill "accepte" button is pressed or item is pressed again. I know that is how text boxes work but i prefer to do it my own way.
Here is my code:
public void createList() {
if (ok == 1) {
//hay muachas possibilidades
if (sol.get(i).getMultiseleccion() != 0){
bt2.setVisibility(View.INVISIBLE);
}else {
//solo se clika en una
//lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
bt2.setVisibility(View.VISIBLE);
}
String hd1 = sol.get(i).getDescSolicitud();
tv2.setText(hd1);
ArrayList<SubSolicitud> sub = sol.get(i).getSubSol();
mAdapter = new EventAdapter(this, sub);
setListAdapter(mAdapter);
lv.setTextFilterEnabled(true);
lv.computeScroll();
lv.setDividerHeight(1);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
ok = 1;
//OnListClick(position, arg1);
if (sol.get(i).getMultiseleccion() != 0) {
// multiples respuestas
((EventEntryView)arg1).text1.setTextColor(Color.YELLOW);
guardarRespuesta();
}else {
buscarElementos();
}
}
});
}
// informar el usuario de que hay un error
else
buildAlertDialog();
}
and the other classes are:
public class EventAdapter extends BaseAdapter {
public ArrayList<SubSolicitud> mEvents = null;
public EventAdapter(Context c, ArrayList<SubSolicitud> subsol) {
mContext = c;
mEvents = subsol;
}
public int getCount() {
return mEvents.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
EventEntryView btv;
if (convertView == null) {
btv = new EventEntryView(mContext, mEvents.get(position));
} else {
btv = (EventEntryView) convertView;
String title1 = mEvents.get(position).getDescripcion();
if (title1 != null) {
btv.setText1Title(title1);
}
}
btv.setBackgroundColor(Color.BLACK);
return btv;
}
private Context mContext;
public void clearEvents() {
mEvents.clear();
notifyDataSetChanged();
}
public void addEvent(SubSolicitud e) {
mEvents.add(e);
}
}
public class EventEntryView extends LinearLayout {
// private View inflatedView;
private TextView text1;
// private TextView text2;
public EventEntryView(Context context, SubSolicitud subSolicitud) {
super(context);
this.setOrientation(VERTICAL);
text1=new TextView(context);
text1.setTextSize(20);
text1.setPadding(10, 10, 10, 10);
text1.setTextColor(Color.WHITE);
String t = subSolicitud.getDescripcion();
text1.setText(t);
addView(text1, new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
}
public void setText1Title(String title1) {
// TODO Auto-generated method stub
text1.setText(title1);
}
}
As you can see I try to get the text in yellow but it doesn't work I click and it doesn't become yellow.
Is there a solution?
thanks
It doesn't work because there is not an EventEntryView for each item in the list - the same EventEntryView is reused to render each.
You need to add something on your SubSolicitud model object to indicate it's been selected (let's say a boolean "selected" property).
In your onItemClicked handler you would toggle this property -
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
// ...
SubSolicitud selectedSubSol = (SubSolicitud)adapterView.getAdapter().getItem(id);
boolean currentValue = selectedSubSol.isSelected();
selectedSubSol.setSelected(!currentValue); // toggle 'selected' on and off
// ...
}
(You also need to fix your EventAdapter getItem method to return mEvents.get(position) for this to work...)
Then in your EventAdapter getView method, you use the value of the "selected" property to render the text color -
public View getView(int position, View convertView, ViewGroup parent) {
// ...
if (mEvents.get(position).isSelected()) {
btv.text1.setTextColor(Color.YELLOW);
} else {
// you have to have an else to set it back to the default
// color, because the view is reused for all list items.
btv.text1.setTextColor(Color.WHITE);
}
// ...
}
This is how you change the color.
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
position = position - listView.getFirstVisibleItem();
((EditText)arg0.getChildAt(position).findViewById(R.id.myTextView)).setTextColor(Color.YELLOW);
}
But if you want to release the item from the color you should iterate through each item of the listview and change it back to normal or you can do it inside the getView() since it is called every time there is action on the listview

Categories

Resources