I'm trying to get an AutoCompleteTextView's ID after I clicked a value on the list. Tried looking up on google and stackoverflow, but the provided answers didn't work. Here's what I've got:
Created the view in my class declaration:
public class ActivityCadastrarCliente extends Activity implements OnClickListener, OnItemClickListener {
AutoCompleteTextView E_Nome_Cliente, E_CPF;
List<String> Nomes = new ArrayList<String>();
...
Associated the view to an XML element:
E_Nome_Cliente = (AutoCompleteTextView)findViewById(R.id.Nome_Cliente);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, Nomes.toArray(new String[0]));
E_Nome_Cliente.setAdapter(adapter);
E_Nome_Cliente.setOnItemClickListener(this);
and my onItemClick method is called normally as below:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//switch (parent.getId()) {
//case R.id.Nome_Cliente:
...
//}
}
Does anybody know how I can access this view inside onItemClick? Tried several ways, but I only get exceptions:
//Class cast exception
AutoCompleteTextView input = (AutoCompleteTextView)view.getParent();
//Class cast exception
AutoCompleteTextView input = (AutoCompleteTextView)parent;
//Class cast exception
AutoCompleteTextView input = (AutoCompleteTextView)parent.getParent();
I need to identify which view was clicked, because I'm using 3 to 5 AutoCompleteTextView and based on the selected value I'll automatically fill in a bunch of other fields.
Have a look at the class AutoCompleteTextViewClickListener in this answer.
Change your setOnItemClickListener call in the following way:
E_Nome_Cliente.setOnItemClickListener(
new AutoCompleteTextViewClickListener(E_Nome_Cliente, this));
Now you can get the id by accessing the modified view parameter:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//view had been modified by AutoCompleteTextViewClickListener
//to contain the original AutoCompleteTextView
switch (view.getId()) {
case R.id.Nome_Cliente:
//...
}
}
An easier way:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Adapter adapter = parent.getAdapter();
if (adapter == autoCompleteTextView1.getAdapter()) {
// Do something
} else if (adapter == autoCompleteTextView2.getAdapter()) {
// Do something else
}
}
i am not sure what do you mean by view id? do you want to get the selected value?
if yes, then the below code will do it, otherwise please clarify more what do you need and why you want to access the view itself.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//switch (parent.getId()) {
String selected = adapter.getItem(position);
//}
}
more on adapter methods are here
Use parent.findViewById(R.id.id_of_autocompleteTextView) on the parent of the AutoCompleteTextView.
Related
I am working on a project which uses a TableLayout, and the user can add a new row to the table layout. Each new row is inflated as a new view and then the view is added to the table layout. One of the controls within the row is an AutoCompleteTextView.
The user can start typing into the AutCompleteTextView and then select one of the items in the suggestion list, when the user selects the item, the selected item is added to the text box as expected, but I want to then set the cursor position as the user can then change the value of the text. For example, the selected item might be sometext() but they can amend the text after selecting it to become sometext(25), so I am trying to set the position of the cursor within the brackets.
This is working fine for one AutoCompleteTextView in the layout but I can't figure out how to do it when its dynamically generated.
I'm finding the AutoCompleteTextView from the inflated layout and creating a set on item click listener, and using the view parameter in the OnItemClick function to ensure I am using the correct view that triggered the event handler, but on the setSelection I am getting an exception java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.AutoCompleteTextView
Below is the code I am using:
private void addRow()
{
TableRow row = (TableRow)LayoutInflater.from(this).inflate(R.layout.create_table_column_row, createTable, false);
txtColumnName = row.findViewById(R.id.txtColumnName);
txtDataType = row.findViewById(R.id.txtDataType);
txtDataType.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
txtDataType.showDropDown();
}
});
txtDataType.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String selectedItem = parent.getItemAtPosition(position).toString();
//Check if the string has a ( and if so, set the cursor to be just after it so the user can enter the size
int bracketPos = selectedItem.indexOf("(");
if (bracketPos > 0)
{
//Crashes on this line
((AutoCompleteTextView)view).setSelection(bracketPos+1);
}
}
});
List<String> datatypes = Arrays.asList(getResources().getStringArray(R.array.table_datatypes));
datatypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, datatypes);
txtDataType.setAdapter(datatypeAdapter);
rowViews.add(row);
createTable.addView(row);
}
I tried casting the view to AppCompatTextView but then this doesn't have the setSelection() method.
The view in onItemClick() is the AppCompatTextView that is clicked in the drop down box for the AutoCompleteTextView. That is why you can't cast it.
Since you have multiple AutoCompleteTextViews, use a focus change listener to capture which AutoCompleteTextView is being addressed by the user. You can then use that value to set the position of the cursor.
private AutoCompleteTextView textView;
private AutoCompleteTextView mAuto;
textView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
mAuto = (AutoCompleteTextView) v;
}
});
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("MainActivity", "<<<<onItemClicked");
int bracketPos = textView.getText().toString().indexOf("(");
if (bracketPos > 0) {
mAuto.setSelection(bracketPos + 1);
}
}
});
I believe that the AutoCompleteTextView is already populated when this method is called, so you could just search for ( within that field.
Here is a slightly different way. After
txtDataType = row.findViewById(R.id.txtDataType);
add
txtDataType.setOnClickListener(new View.OnClickListener() {
private AutoCompleteTextView mAutoView;
#Override
public void onClick(View v) {
mAutoView = (AutoCompleteTextView) v;
mAutoView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("MainActivity", "<<<<onItemClicked");
int bracketPos = mAutoView.getText().toString().indexOf("(");
if (bracketPos > 0) {
mAutoView.setSelection(bracketPos + 1);
}
}
});
}
});
You can delete your other listeners.
i create in a two way data binding spinner in Android, and added value into with a result of a REST GET.
I need now to add the first value of the spinner as an empty string that when it will be selected from the spinner, the value will be null.
In the fragment class i wrote this code:
//spinner
appCompatSpinner = binding.spinner;
spinnerAdapter = new SpinnerAdapter(getActivity(), viewModel.usersDetailsList );
appCompatSpinner.setAdapter(spinnerActorAdapter);
appCompatSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
viewModel.onSelected(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mAdapter.notifyDataSetChanged();
Can someone please help me to achieve that?
I am working on my first ever android app, and I'm creating basic exercise/calorie counter. I have two spinners, one for the selected type of exercise, and one for the time spent preforming said exercise in minutes. I need to be able to check the value/position of both spinners so I can do something like this:
PSUEDO CODE:
if(Exercise spinner = "push-ups")
{
CaloriesBurned = TimeSpinnerValue*450
}
if(Exercise spinner = "sit-up")
{
CaloriesBurned = TimeSpinnerValue*350
}
etc . . . nothing fancy. My spinners are populated from a String Array in my String.xml. But I dont know how get the value of the spinner so I can use it in some IF statements in my java code.
use like this for compair any string with your spinner.
spinner.equals("push-ups");
You need to implement OnItemSelectedListener for getting the selected value from the Spinner. Then override,
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
int id = parent.getId();
switch (id) {
case R.id.first_spinner:
// your stuff here
break;
case R.id.second_spinner:
// your stuff here
break;
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
yourSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
String selectedString = (String) (yourSpinner.getAdapter()).getItem(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
check this link fro more info
Generically, you'll want to follow this pattern:
SpinnerAdapter adapter = Spinner.getAdapter();
int position = Spinner.getSelectedItemPosition();
Object value = adapter.getItem(position);
Since you are loading it with String values, you can then cast value to a String.
Have some field in your activity to hold value of spinner, initialize with some defaultvalue
implement onItemSelectedListener on spinners, and in onItemSelected get value of selected item, by position argument of onItemSelected(AdapterView adapterView, View view, int position, long id)
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
How do I listen to click event on a ListView?
This is what I have now
ListView list = (ListView)findViewById(R.id.ListView01);
...
list.setAdapter(adapter);
When I do the following
list.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView parentView, View childView,
int position, long id)
{
setDetail(position);
}
public void onNothingSelected(AdapterView parentView) {
}
});
That doesn't seem to do anything on click.
And all those code live within a class that extends Activity.
On your list view, use setOnItemClickListener
Suppose ListView object is lv, do the following-
lv.setClickable(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = lv.getItemAtPosition(position);
/* write you handling code like...
String st = "sdcard/";
File f = new File(st+o.toString());
// do whatever u want to do with 'f' File object
*/
}
});
You need to set the inflated view "Clickable" and "able to listen to click events" in your adapter class getView() method.
convertView = mInflater.inflate(R.layout.list_item_text, null);
convertView.setClickable(true);
convertView.setOnClickListener(myClickListener);
and declare the click listener in your ListActivity as follows,
public OnClickListener myClickListener = new OnClickListener() {
public void onClick(View v) {
//code to be written to handle the click event
}
};
This holds true only when you are customizing the Adapter by extending BaseAdapter.
Refer the ANDROID_SDK/samples/ApiDemos/src/com/example/android/apis/view/List14.java for more details
The two answers before mine are correct - you can use OnItemClickListener.
It's good to note that the difference between OnItemClickListener and OnItemSelectedListener, while sounding subtle, is in fact significant, as item selection and focus are related with the touch mode of your AdapterView.
By default, in touch mode, there is no selection and focus.
You can take a look here for further info on the subject.
This solution is really minimalistic and doesn't mess up your code.
In your list_item.xml (NOT listView!) assign the attribute android:onClick like this:
<RelativeLayout android:onClick="onClickDoSomething">
and then in your activity call this method:
public void onClickDoSomething(View view) {
// the view is the line you have clicked on
}
You have to use setOnItemClickListener someone said.
The code should be like this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text or do whatever you need.
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
First, the class must implements the click listenener :
implements OnItemClickListener
Then set a listener to the ListView
yourList.setOnItemclickListener(this);
And finally, create the clic method:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +countries[+ position], Toast.LENGTH_SHORT).show();
}
you can take a look and download code here
Use setOnItemClickListener() api in your activity. Following is the sample.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<> parent, View view, int position, long id)
{
// your code here.
}
});
In Kotlin, add a listener to your listView as simple as java
your_listview.setOnItemClickListener { parent, view, position, id ->
Toast.makeText(this, position, Toast.LENGTH_SHORT).show()
}