I have a button and Spinner in ListView item. I've put the below code inside setOnItemSelectedListener of Spinner.
String val = viewHolderItem.spinnerSize.getSelectedItem().toString();
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
But it doesn't change inside the setOnItemSelectedListener. But when I put the same code inside setOnClickListener of the Button then it wroks and changed the value of the object. What is the reason for this?
GetView method :
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolderItem viewHolderItem;
final Shoe shoe = shoeList.get(position);
if(convertView == null){
LayoutInflater inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.component_order_shoe_row,null);
viewHolderItem = new ViewHolderItem();
viewHolderItem.tvName = (TextView)convertView.findViewById(R.id.tv_component_order_shoe_name);
viewHolderItem.tvPrice = (TextView)convertView.findViewById(R.id.tv_component_order_shoe_price);
viewHolderItem.tvDesc = (TextView)convertView.findViewById(R.id.tv_component_order_shoe_description);
viewHolderItem.ivPic = (ImageView)convertView.findViewById(R.id.iv_component_order_shoe_pic);
viewHolderItem.ivTick = (ImageView)convertView.findViewById(R.id.iv_component_order_shoe_tick);
viewHolderItem.spinnerSize = (Spinner)convertView.findViewById(R.id.spinner_component_order_shoe_size);
viewHolderItem.etQty = (EditText)convertView.findViewById(R.id.et_component_order_shoe_qty);
viewHolderItem.btnOrder = (Button)convertView.findViewById(R.id.btn_component_order_shoe_order);
viewHolderItem.btnOrder.setTag(viewHolderItem);
convertView.setTag(viewHolderItem);
}else{
viewHolderItem = (ViewHolderItem)convertView.getTag();
}
viewHolderItem.tvName.setText(shoe.getShoeName());
String text = String.valueOf(shoe.getPrice());
int integerPlaces = text.indexOf('.');
int decimalPlaces = text.length() - integerPlaces - 1;
if(decimalPlaces==1){
viewHolderItem.tvPrice.setText("Rs."+ text + "0");
}else{
viewHolderItem.tvPrice.setText("Rs."+ text);
}
if(shoe.isSelected()){
viewHolderItem.ivTick.setImageDrawable(mContext.getResources().getDrawable(R.drawable.tick));
viewHolderItem.btnOrder.setText(mContext.getResources().getString(R.string.btn_remove_shoe_item));
}else{
viewHolderItem.ivTick.setImageDrawable(null);
viewHolderItem.btnOrder.setText(mContext.getResources().getString(R.string.btn_order_shoes));
}
viewHolderItem.tvDesc.setText(shoe.getDesc());
Bitmap bmp = AppControl.convertStringToBitmap(shoe.getImg());
viewHolderItem.ivPic.setImageBitmap(bmp);
int smallest = shoe.getSmallestSize();
int largest = shoe.getLargestSize();
Integer[] arr = getSizeArray(smallest,largest);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(mContext, android.R.layout.simple_spinner_dropdown_item,arr);
viewHolderItem.spinnerSize.setAdapter(adapter);
viewHolderItem.btnOrder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewHolderItem viewHolder = ((ViewHolderItem) v.getTag());
boolean isSelected = shoe.isSelected();
if(isSelected){
((Button)v).setText(mContext.getResources().getString(R.string.btn_order_shoes));
viewHolder.ivTick.setImageDrawable(null);
viewHolder.etQty.setEnabled(true);
isSelected = false;
}else{
((Button)v).setText(mContext.getResources().getString(R.string.btn_remove_shoe_item));
viewHolder.ivTick.setImageDrawable(mContext.getResources().getDrawable(R.drawable.tick));
viewHolder.etQty.setEnabled(false);
isSelected = true;
}
shoeList.get(position).setSelected(isSelected);
String input = viewHolderItem.etQty.getText().toString();
if(isEnteredValueNumeric(input)){
shoeList.get(position).setQty(Integer.parseInt(input));
}else{
shoeList.get(position).setQty(1);
AppControl.showToastMessage(mContext,Constant.MSG_NOT_A_NUMBER);
viewHolderItem.etQty.setText(String.valueOf(1));
}
String val = viewHolderItem.spinnerSize.getSelectedItem().toString();
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
}
});
viewHolderItem.spinnerSize.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String val = parent.getItemAtPosition(position).toString();
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});
return convertView;
}
You made a mistake here:
String val = parent.getItemAtPosition(position).toString();
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
The position value for shoeList is not the same as the position value for the shoeSize Spinner item. Try changing the onItemSelected method position name parameter to something like pos. So let your getView keep using final int position but in onItemSelected for shoeSize use:
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
String val = parent.getItemAtPosition(pos)
.toString();
shoeList.get(position).setSelectedSize(
Integer.parseInt(val));
}
Inside your onClickListener's their is not any parameter for position as integer in onClickMethod:
#Override
public void onClick(View v) {
/* so this position in shoeList.get(position) returns the position of the
* list view item i.e you array list exact position*/
shoeList.get(position).setSelectedSize(Integer.parseInt(val));
}
but in you onItemSelected their is a position value already exists so you may need to change it's parameter name like:
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
// just like #electrocrat insist
String val = parent.getItemAtPosition(pos)
.toString();
shoeList.get(position).setSelectedSize(
Integer.parseInt(val));
}
you may also can do this via setting tag to viewHolderItem.spinnerSize as
viewHolderItem.spinnerSize.setTag(position) and inside the onItemSelected you can get the position via (Integer)parent.getTag(), like:
shoeList.get((Integer)parent.getTag()).setSelectedSize(
Integer.parseInt(val));
Related
I am having issues trying to restore state of Android Spinners in my application. Currently there are multiple Spinners in my Activity's ListView header that depend on one another, as the selection of one Spinner loads data for the subsequent Spinner.
The problem I am experiencing is, restoring state doesn't seem to work when I manually set selections on the Spinners. I have tried in both onRestoreInstanceState and onResume. It appears setting the selections is asynchronous when looking at the LogCat output. How can I reliably restore state of these Spinners when I have to wait for one to be selected before the other can populated and then set?
EDIT: Added code
Activity's onCreate():
mSecondSpinner = mMyListHeader.findViewById(R.id.second_spinner);
mSecondSpinnerArrayAdapter = new SecondArrayAdapter(MyActivity.this, R.layout.second_spinner_item, new ArrayList<MySecondDto>());
mSecondSpinner.setAdapter(mSecondSpinnerArrayAdapter);
mSecondSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
MySecondDto selectedMySecondDto = (MySecondDto) parent.getItemAtPosition(position);
List<MyThirdDto> myThirdDtos = selectedMySecondDto.getMyThirdDtos();
// Load third spinner with dtos....
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}}
);
mFirstSpinner = mMyListHeader.findViewById(R.id.first_spinner);
mFirstSpinnerAdapter= new FirstArrayAdapter(MyActivity.this, R.layout.first_spinner, mResponse.getAllDtos());
mFirstSpinner.setAdapter(mFirstSpinnerArrayAdapter);
mFirstSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mSecondSpinner.setAdapter(null);
MyFirstDto selectedMyFirstDto = (MyFirstDto ) parent.getItemAtPosition(position);
List<MySecondDto> mySecondDtos = selectedMyFirstDto .getMySecondDtos();
mSecondSpinnerArrayAdapter.clearAndReplaceAll(mySecondDtos);
mSecondSpinner.setAdapter(mSecondSpinnerArrayAdapter);
// If there is only one second dto, disable the spinner
if (mySecondDtos== null || mySecondDtos.size() <= 1)
{
disableSpinner(mSecondSpinner);
}
else
{
// Enable second spinner, select the hint element
enableSpinner(mSecondSpinner);
mSecondSpinner.setSelection(mSecondSpinnerArrayAdapter .getHintIndex());
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {}
});
Activity's onRestoreInstanceState():
mFirstSpinner.setSelection(mFirstAdapterPosition);
mFirstSpinnerArrayAdapter.notifyDataSetChanged();
mSecondSpinner.setSelection(mSecondAdapterPosition);
mSecondSpinnerArrayAdapter.notifyDataSetChanged();
Have u tried this
mySpinner.post(new Runnable() { #Override public void run() { mySpinner.setSelection(position); } });
This might work for you.
There could be a bug in it somewhere, so be careful.
I have a similar situation to you but I had 3 spinners and they get populated depending on the selection of the previous one.
The idea is to store the Indexes/Positions of the Spinners in IndexVariables.
Theses Variables have default value of -1.
Store current values in onSaveInstanceState,
Restore values in onActivityCreated.
In onItemSelected check if selected Item = null, check if the IndexVariable was set (i.e. !-= -1)
If so use it to set Spinner then set IndexVariable back to -1;
Here's the class
(I used NothingSelectedSpinnerAdapter from How to make an Android Spinner with initial text "Select One".
Not really important but just giving a shout out to the guy/girl where I got that code.)
public class SpinnerTestFragment extends Fragment {
private MainActivity activity;
private static final String SELECTED_THEME_IDX_STORAGE_KEY = "mSelectedTheme_IDX_StorageKey";
private static final String SELECTED_AIM_IDX_STORAGE_KEY = "mSelectedAim_IDX_StorageKey";
private static final String SELECTED_GOAL_IDX_STORAGE_KEY = "mSelectedGoal_IDX_StorageKey";
private static String TAG = "SpinnerTestFragment";
private Spinner spnrThemes;
private Spinner spnrAims;
private Spinner spnrGoals;
private String mSelectedTheme;
private String mSelectedAim;
private String mSelectedGoal;
private int mSelectedAimIdx = -1;
private int mSelectedThemeIdx = -1;
private int mSelectedGoalIdx = -1;
//----------------------------------------------------------------------------------------//
public SpinnerTestFragment() {
}//ctor
//----------------------------------------------------------------------------------------//
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
activity = (MainActivity) getActivity();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_photo, container, false);
spnrThemes = view.findViewById(R.id.spnrThemes);
spnrAims = view.findViewById(R.id.spnrAims);
spnrGoals = view.findViewById(R.id.spnrGoals);
setSpinner(spnrThemes, "Select Theme", ThemesAimsGoals.getThemes());
spnrThemes.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedTheme = selectedItem.toString();
setSpinner(spnrAims, "Select Aim", ThemesAimsGoals.getAims(mSelectedTheme));
} else if(mSelectedThemeIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedThemeIdx);
mSelectedTheme = selectedItem.toString();
setSpinner(spnrAims, "Select Aim", ThemesAimsGoals.getAims(mSelectedTheme));
parent.setSelection(mSelectedThemeIdx);
mSelectedThemeIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spnrAims.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedAim = selectedItem.toString();
setSpinner(spnrGoals, "Select Goal", ThemesAimsGoals.getGoals(mSelectedTheme, mSelectedAim));
} else if(mSelectedAimIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedAimIdx);
mSelectedAim = selectedItem.toString();
setSpinner(spnrGoals, "Select Goal", ThemesAimsGoals.getGoals(mSelectedTheme, mSelectedAim));
parent.setSelection(mSelectedAimIdx);
mSelectedAimIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spnrGoals.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object selectedItem = parent.getItemAtPosition(position);
if (selectedItem != null) {
mSelectedGoal = selectedItem.toString();
}else if(mSelectedGoalIdx != -1){
selectedItem = parent.getItemAtPosition(mSelectedGoalIdx);
mSelectedGoal = selectedItem.toString();
parent.setSelection(mSelectedGoalIdx);
mSelectedGoalIdx = -1;
}//Else
}//onItemSelected
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return view;
}//onCreateView
//----------------------------------------------------------------------------------------//
/**
* Populate Spinner
* #param spnr Spinner to populate
* #param prompt What to show at the start
* #param array Items in the spinner
*/
private void setSpinner(Spinner spnr, String prompt, String[] array) {
spnr.setPrompt(prompt);
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(activity, android.R.layout.simple_spinner_item, array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnr.setAdapter(
new NothingSelectedSpinnerAdapter(
adapter,
R.layout.contact_spinner_row_nothing_selected,
activity,
prompt));
}//setSpinner
//----------------------------------------------------------------------------------------//
/**
* Some lifecycle callbacks so that the image can survive orientation chang
*
* #param outState current state of fragment
*/
#Override
public void onSaveInstanceState(Bundle outState) {
Log.d(TAG, "onSaveInstanceState");
super.onSaveInstanceState(outState);
outState.putInt(SELECTED_THEME_IDX_STORAGE_KEY, spnrThemes.getSelectedItemPosition());
outState.putInt(SELECTED_AIM_IDX_STORAGE_KEY, spnrAims.getSelectedItemPosition());
outState.putInt(SELECTED_GOAL_IDX_STORAGE_KEY, spnrGoals.getSelectedItemPosition());
}//onSaveInstanceState
//----------------------------------------------------------------------------------------//
/**
* Rebuilds the Activity/Fragment in the image of the last one.
*
* #param savedInstanceState Info from last session or rotation
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.d(TAG, "onActivityCreated");
if (savedInstanceState == null)
return;
mSelectedThemeIdx = savedInstanceState.getInt(SELECTED_THEME_IDX_STORAGE_KEY);
mSelectedAimIdx = savedInstanceState.getInt(SELECTED_AIM_IDX_STORAGE_KEY);
mSelectedGoalIdx = savedInstanceState.getInt(SELECTED_GOAL_IDX_STORAGE_KEY);
}//onActivityCreated
}//Cls
As a continuation of the question here, I found that the listener of the spinner is never executed (or) triggered and I am not able to solve the issue.
Here is the part of the code with the spinner and the listener:
Spinner priority = (Spinner)findViewById(R.id.priority);
priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("listener","it works");
Log.d("value",""+parent.getSelectedItem().toString().equalsIgnoreCase("Low"));
/*if(parent.getSelectedItem().toString().equalsIgnoreCase("Low"))
imageId = R.drawable.blue;
else if(parent.getSelectedItem().toString().equalsIgnoreCase("Medium"))
imageId = R.drawable.green;
else
imageId = R.drawable.red;*/
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
In the log, the values of listener and value are not printed at all.
Modified code.
Spinner priority = (Spinner)findViewById(R.id.priority);
priority.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d("listener","it works");
//Instead of doing parent.getSelectedItem(), get the adapter from parent and from that adapter get item at position as below.
Log.d("value",""+parent.getAdapter().getItem(position).toString().equalsIgnoreCase("Low"));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
If your data is string then it will work else you are passing any custom object then you need to cast result from this parent.getAdapter().getItem(position) to that custom object class.
Finally found the solution :
String priortyStr = priority.getSelectedItem().toString();
int imageId = 0;
if(priortyStr.equals("Low"))
imageId = R.drawable.blue;
else if(priortyStr.equals("Medium"))
imageId = R.drawable.green;
else
imageId = R.drawable.red;
I have an OnItemClick(), after that I wanted to get the ItemClicked name's and display it in a TextView.I do it normally, but the problem is that I get the ItemClicked name's inside a bracket! How do I avoid this?Here is the output:
{titre=hello}
I want only in my TextView:
hello.
Here is the code:
public void onItemClick(AdapterView<?> parent, View view, int position, long id ) {
displayTextViewTitle = (TextView)findViewById(R.id.text_view_title);
Object item = parent.getItemAtPosition(position);
String value = item.toString();
displayTextViewTitle.setText(String.valueOf(value));
}
Try this :
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
TextView item = (TextView) parent.getItemAtPosition(position);
String value = item.getText();
displayTextViewTitle.setText(value);
}
or even better try :
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
ListView lv = (ListView) findViewById(yourListViewName);
String value = lv.get(position).tostring();
displayTextViewTitle.setText(value);
}
If you are getting your String {titre=hello} like this after click on ListView. then you should use this:
String[] no = item.split("=");
String m = no[0];
String k = no[1];
String name = k.substring(0, k.length() - 1);
name is your final result String .
value is already a String, you don't have to use String.valueOf(value).
The listener method works fine, check this:
public class SplashActivity extends Activity implements OnItemClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
ListView lv = (ListView)findViewById(R.id.lv);
ArrayList<String> members = new ArrayList<String>();
members.add("titre=hello");
members.add("world");
ArrayAdapter s = new ArrayAdapter(this, android.R.layout.simple_list_item_1, members);
lv.setAdapter(s);
lv.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
TextView displayTextViewTitle = (TextView) findViewById(R.id.textView1);
Object item = parent.getItemAtPosition(position);
String value = item.toString();
displayTextViewTitle.setText(String.valueOf(value));
}
}
Recheck the values inside your listview, the problem might be there
I have an array (array1 with States) and AutoCompleteTextview in which I'm filling it with array1. When I select the value from AutocompleteTextView I select a state from AutoCompleteTextView Dropdown
What I want is to get the position of the item from array1 which I've selected.
What I've tried is OnClickEvent of AutocompelteTextView.
STATE.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String) parent.getItemAtPosition(position);
String num = selection;
}
});
It ss giving me the value which I selected from dropdown but i want to get the position of the value in array1. For Example I have an array of size 4, like array1 = {A,B,C,D}, and if I select B it should return me B position in Array i.e 2.
I hope I made it clear. Thanks in advance.
Use the position variable in the onItemClick.
STATE.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String) parent.getItemAtPosition(position);
int pos = -1;
for (int i = 0; i < yourarray.length; i++) {
if (yourarray[i].equals(selection)) {
pos = i;
break;
}
}
System.out.println("Position " + pos); //check it now in Logcat
}
});
Use List instead of Array. Implement onItemClickListener for AutoCompleteTextView, then use indexOf on your list to find the index of selected item.
actvCity.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int index = cityNames.indexOf(actvCity.getText().toString());
// Do Whatever you want to do ;)
}
});
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
TextView txtvw=(TextView) view;
String str=txtvw.getText().toString();
int index = contactNames.indexOf(str);
}
Item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//// id contains item if from database
ItemNoSelected = id;
}
});
id is from database, we can use that
You can find the parent string in the clickItem listener.
OSchools in this case is the custom ArrayList.
Object item = parent.getItemAtPosition(position);
for(OSchools d : data){
Log.e("name",d.getName());
String name = d.getName();
if(d.getName() != null && name.contains(item.toString())){
ID = d.getID();
}
When I use edit text to filter the items, the list positions get all messed up and the items no longer call the proper intent. Any help is appreciated
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String mName = filteredValues.get(position).getName().toString();
String mWeb = filteredValues.get(position).getWebsite().toString();
Intent openDetails = new Intent(Test.this, ResourceDetails.class);
Bundle b = new Bundle();
b.putString("name", mName);
b.putString("web", mWeb);
openDetails.putExtras(b);
startActivity(openDetails);
}
});
private TextWatcher filterTextWatcher = new TextWatcher(){
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
}
public void afterTextChanged(Editable s) {
}
};
flashsearchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Integer temp=flashSearchNameMap.get(adapter.getItem(position));
navigateSearch(temp);
}
});
(adapter.getItem(position) will return you the exact list name and in flashSearchNameMap i have stored names and position at beginning from oncreate before applying filtering.So you can get exact position by this
if you use ViewHolder in Adapter just define a realPosition variable in holder class and set it in YourAdapter.getView
and in listClick Listener
ContactAdapter.ViewHolder holder = (YourAdapter.ViewHolder) view.getTag();
holder.realPosition
The item position is not reliable when using lists. I recommend you to use view.setTag(Object) to assign an identifier to each item when attaching the content. This could be a number, string or anything. Then you can just access it with view.getTag() inside the click listener.
Assuming you are using a custom bean object to store your name & website values and an ArrayAdapter to show them in your ListView, like so
public class NamedLink {
final String mName;
final String mWebsite;
public NamedLink(String name, String website) {
mName = name;
mWebsite = website;
}
#Override
public String toString() {
return mName;
}
}
With an adapter, defined something like this:
mAdapter = new ArrayAdapter<NamedLink>(this, android.R.layout.simple_list_item_2, mLinks) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(WhateverYourActivityIsNamed.this).inflate(android.R.layout.simple_list_item_2, null);
}
NamedLink link = getItem(position);
// This probably deserves a ViewHolder
((TextView) convertView.findViewById(android.R.id.text1)).setText(link.getName());
((TextView) convertView.findViewById(android.R.id.text2)).setText(link.getWebsite());
return convertView;
}
};
When you filter the array adapter it will match against the beans #toString(), which in this case returns the name. When filtered, the array adapter maintains a properly indexed copy of your list of beans internally - i.e. you can use the position you get in the click listener like this:
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getItemAtPosition() will return a NamedLink from the filtered
// list maintained inside the ArrayAdapter
NamedLink link = (NamedLink) parent.getItemAtPosition(position);
Intent openDetails = new Intent(Test.this, ResourceDetails.class);
Bundle b = new Bundle();
b.putString("name", link.getName());
b.putString("web", link.getWebsite());
openDetails.putExtras(b);
startActivity(openDetails);
}
});