Set Text based on list item click - android

I am having a layout consisting of ListView and a label. Look at the image below.
I implemented listview using base adapter in a seperate .java file.
Could anyone suggest me how can i set text to the label on click of list item?
EDITED :
The text of the label should be number of list items clicked.
Suppose i clicked a button in a list item, the label should be set to 1.
Similarly in the next attempt if i clicked another list item's button it should be set to 2 and so.. on..

Sir,
What you are saying is this, you have your adapter in one class and the activity in another file. Well you could do this, to update the textview.
pass the context to the activity, and if its in the adapter you are maintaining the count then once the count has been updated,
then, assume you have this method in the activity
public void updateTextView(int count) {
// enter your code here to set the count in the textview
}
and from the baseAdapter call the above method like this:
if(mContext != null) {
((YourActivity)mContext).updateTextView(mCount);
}
and the textview in the activity will be updated!
I hope it helps.

In your OnItemClickListener call adapter.getItem(int position) to retrieve the object from the collection backing your BaseAdapter. From there, you should be able to retrieve any fields you need.
Edit:
Your edit clears up the question. Updated answer:
private int mCounter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ListView listView = getYourListView();
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mCounter++;
updateTextView();
}
});
if(savedInstanceState != null) {
mCounter = savedInstanceState.getInt("counter", 0);
}
updateTextView();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("counter", mCounter);
}
private void updateTextView() {
// TextView textView = getYourTextView();
textView.setText(String.valueOf(mCounter));
}

Just OnItemClickListener in your ListView then in the onClick you will get a value arg2 which is the position of the item which is clicked.
Just get that value from the ArrayList from which you are displaying the ListView and show it...
Hope this is what you need if I have not misunderstood your question.

try this code
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
String itemText=(String) arg0.getItemAtPosition(arg2);
yourLable.setText(itemText);
}
});

In onListItemClick call list.getItemAtPosition(position) to retrieve item text
then set this text to textview1.setText(listText).

First Implement your onItemClickListener, where you will get int arg2 parameter, which is position, so get that position and do your stuff whatever you want like below.
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
LABLE.setText(""+arg2);
}
});

Check this code
public class ListA extends ListActivity {
private TextView selection;
private static final String[] items={"Item 1", "Item 2", "Item 3"};
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_list);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
items));
selection=(TextView)findViewById(R.id.selection);
}
#Override
public void onListItemClick(ListView parent, View v, int position,
long id) {
selection.setText(position);
}
}

Related

How can I click a button to launch an ItemSelected event of spinner control?

I have a spinner control with setOnItemSelectedListener in my app, when I select an item of the spinner, the event onItemSelected will be launched.
Now I hope to click a button to launch the onItemSelected event, how can I do? Thanks!
spinnerFolder.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
//Do Business Logic
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Just call the following from your button listener:
spinnerFolder.getOnItemSelectedListener().onItemSelected(spinnerFolder, spinnerFolder.getSelectedView(), spinnerFolder.getSelectedItemPosition(), spinnderFolder.getSelectedItemId());
That's all :-)
The third parameter (int arg2) of onItemSelected for your spinner is the position, so you can get the current selection by
String selection = (String) mSpinnerAdapter.getItem(position);
or use mSpinner.getItemAtPosition(position) if you don't have a custom adapter.
Store the current selection somewhere and pick it up in the onClickListener for your button.
When you populate the spinner with some data, you will have some sort of list objects (Strings, custom object, whatever) in the SpinnerAdapter, you'll keep a reference to that list, let's call it: private List<Object> dataList = ...
First of all I would create a method that would handle the specific data object:
protected void doBusinessLogic(Object myObj) {
// do the things that make you happy
}
Then call this from listener as:
spinnerFolder.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// args2 is the position from backed data list
doBusinessLogic(dataList.get(args2));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Then from button listener you would call above method again, but the object index you would get is from spinnerFolder.getSelectedItemPosition();:
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int dataIndex = spinnerFolder.getSelectedItemPosition();
doBusinessLogic(dataList.get(index));
}
});

Android: trying to get response when person clicks on a item in list box

I'm just learning how to use ListViews. I got it working, but wont to be able to respond when some one clicks a item.
I'm trying to use the setOnItemClickListener method to take a call back for when a item is clicked on. But my code will not compile due to errors in method setOnItemClickListener
r
Right now i get a error that says
setOnItemClickListener is not applicable for arguments OnItemClickListener();
void SetUpList()
{
listView = (ListView) findViewById(R.id.mylist);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile"};
EventsAdapter adapter = new EventsAdapter(this, cGlobals.eventsTitle);
// Assign adapter to ListView
listView.setAdapter(adapter);
// this is whare I get the error listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
}
});
}
}
First make sure you have imported this class:
import android.widget.AdapterView.OnItemSelectedListener;
Next you need to call setOnItemClickListener() like so:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override // "#Override" is required for Java 1.6, but forbidden in 1.5
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Do Something
}
});
Or if your activity implements OnItemClickListener: You need to add the onItemClick() method outside your onCreate() method:
#Override
public void onCreate(Bundle savedInstanceState) {
// Do Something
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Do something else
}
(Of course, if you are extending a ListActivity or ListFragment you should override onListItemClick() instead of onItemClick() like the second approach.)

2 ListViews in the same activity

If I have 2 or more listviews in one activity,then how do I use a onclicklistener? I mean How do I know on which one of them the user click?
public void onItemClick(AdapterView parent, View v, int position, long id) {
}
The above code is what I used,however when I try to use another listview,I just can't find a way to detect which listview is clicked.
Any ideeas to solve this?
In this case, the parent is the listView from which the itemClick originated. So what you can do is keep a member variable for each ListView and compare the parent to those members to see which list triggered the click.
So here's a simple class with what I mean:
public class MyTest extends Activity{
private ListView list1;
private ListView list2;
public void onCreate(Bundle b){
super.onCreate(b);
list1 = new ListView();
list2 = new ListView(); //or findViewById if you declared them in your layout
//the rest of your creation code here
}
public void onItemClick(AdapterView parent, View v, int position, long id) {
if(list1 == parent){
//handle list1 click
}else{
//handle list 2 click
}
}
}
There are two ways you can do it.
Implement OnItemClickListener
public class ListViewTest extends Activity implements OnItemClickListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
if(view ==myListView)1{
}
if(view ==myListView){
}
}
}
Set your own listener
myListView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on second listview
}
});
You can do it as this:
listView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on first listview
}
});
listView2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO: click on second listview
}
});
its pretty simple ,
only one list can act as the official list under a ListActivity and this list (and only this list) should have the special list id (#android:list i think) so just set the id of the other list to some other id and set its setOnItemClickListener to do whatever you want. I currently work on an app with 2 listViews and an additional list Fragment.

How to get text from AutoCompleteTextView?

I have an AutoCompleteTextView in my app which works. I have successfully created an onClickItemListener. The question is how to grab the text the user selected.
And this is the thing: I have an ArrayList with words being passed to the Adapter to search for suggestions. As the user types a word the suggestions list gets shorter (in rows on the UI side) so when i want to get the word from the ArrayList at the index the user selected i get the wrong word because the indexes doesn't match.
How can I get the text (String) the user chose without having to mess with the index?
Here's my code:
public class AutocompleteActivity extends BaseActivity {
private DBManager m_db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.autocomplete);
m_db = new DBManager(this);
final ArrayList<String> words = m_db.selectAllWords();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, words);
AutoCompleteTextView tv = (AutoCompleteTextView)findViewById(R.id.autocomplete);
tv.setThreshold(1);
tv.setAdapter(adapter);
tv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Log.i("SELECTED TEXT WAS------->", words.get(arg2));
}
});
}
}
Yeah... unfortunately the name of the parameters on the onItemClick method you must implement are not so self-descriptive but here is an example with the names of what they are:
autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long rowId) {
String selection = (String)parent.getItemAtPosition(position);
//TODO Do something with the selected text
}
});
parent The AdapterView where the click happened.
view The view within
the AdapterView that was clicked (this will be a view provided by the
adapter)
position The position of the view in the adapter
id The row id of the item that was clicked.
For more info see: http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html
arg0 being your AdapterView and arg2 the position.
Have you tried:
arg0.getItemAtPosition(arg2);
I think what you are looking for is this.
String s = this.mCountry.getEditableText().toString();
Where mCountry is the AutoCompleteTextView.
this.mCountry = (AutoCompleteTextView) findViewById(R.id.autocomplete_country);
ArrayAdapter<String> adapterCountry = new ArrayAdapter<String>(this, R.layout.list_item, countries);
this.mCountry.setAdapter(adapterCountry);
mCountry is the list of countries, and I wanted to save the country selected in SharedPreferences.
Hope this helps.
Easiest of all
For Getting text of the selected suggestion in AutoCompleteTextView use this
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.e("========>>", autoCompleteTextView.getText().toString());
}
});
try this:
txtPurpose.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Purpose selected = (Purpose) arg0.getAdapter().getItem(arg2);
txtPurpose.setTag(selected);
}
});
One another of getting text of suggestion selected in AutoCompleteTextView is
#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);
}
Here is the code that will solve the problem.
private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
int index = (int) view.getTag();
Object item = parent.getItemAtPosition(index);
if (item instanceof SearchItemShareConnectionDAO) {
SearchItemShareConnectionDAO dao = (SearchItemShareConnectionDAO) item;
}
}
};
SetTag(Dao.getPosition) in getView() method of adapter.
To get the text of the displayed item selected by the user
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
String selectedItemText = arg0.getItemAtPosition(arg2);
Log.i("myTag", "SELECTED TEXT WAS["+selectedItemText+"]);
}
Following best practices, please use some form of descriptive nomenclature for your variables, your code will make more sense:
public void onItemClick(AdapterView<?> adapterViewIn, View viewIn, int selectedItemIndexIn, long id)
There is also a way to get item outside the onItemClick:
int index = tv.getListSelection();
if (index != ListView.INVALID_POSITION) {
Object item = tv.getAdapter().getItem(index);
}
beware that int getListSelection() may return ListView.INVALID_POSITION if there is no dropdown or if there is no selection.
For me, but on setOnItemSelectedListener():
arg0.getSelectedItem();
was enough. The same should work on setOnItemClickListener() I guess.
Kotlin version
autoCompleteId.setOnItemClickListener { parent, view, position, id ->
val selectedItem = parent.getItemAtPosition(position).toString()
Log.d("SELECTED ITEM", selectedItem )
}
Output:
D/CLASSROOM: selectedItem

Getting the selected item from a ListView

Please Help me for getting the selected Item from a ListView. Items for the ListView are getting from a xml file. Elements of the ListView are filled up by the adapter(adpter contains ImageView and textView). I only need the TextView content from the ListView.By using the onItemClick i get only the index of the item.
Thank You
Using getSelectedItem() is the correct thing to do. You get a null value back when no item is selected.
If I remember true, getSelectedItem() just use if your Activity is ListActivity.
In normal Activity, and you add a component ListView. here is an example code, wish you can follow it :
private ListView listContainer; public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
listContainer = (ListView) findViewById(R.id.listContainer);
listContainer.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adView, View target, int postion, long id) {
alert("notice", "you have selected: " + id); }
});
protected void alertbox(String title, String mymessage) {
new AlertDialog.Builder(this).setMessage(mymessage).setTitle(title).setCancelable(true)
.setNeutralButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){}
}).show();
}

Categories

Resources