Which is the most recommended way of handling click on RecyclerView items?
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
private RecyclerView.OnItemTouchListener itemTouchListener;
#Override
public boolean onInterceptTouchEvent(#NonNull RecyclerView recyclerView, #NonNull MotionEvent motionEvent) {
return false;
}
#Override
public void onTouchEvent(#NonNull RecyclerView recyclerView, #NonNull MotionEvent motionEvent) {}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {}
});
Or setting a click listener on an item view inside the adapter?
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do stuff
}
});
A Best and efficient way to get a click of recycler view item is by using interface as below:
1) First, define one interface as below
public interface OnListItemClick {
void onClick(View view, int position);
}
2) Now, set it from your fragment or activity
OnListItemClick onListItemClick = new OnListItemClick() {
#Override
public void onClick(View view, int position) {
// you will get click here
// do your code here
}
};
youradaptor.setClickListener(onListItemClick);
3) Now create one method in your adapter
public void setClickListener(OnListItemClick context) {
this.onListItemClick = context;
}
4) Now, from your itemview click use as below
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onListItemClick.onClick(view, getAdapterPosition()); // passing click to interface
}
});
Most common way it to use interfaces to handle onClick events inside a Recycler View.
Great read about this topic here
Go for your second opinion. But an interface should be implemented to handle the OnClick Event
I have spinner and edittext, and i want if spinner is selected can setfocus in edittext. I am already try, but not going to work, how to fix this?
This is my code :
edkontak1.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_NEXT) {
sembunyikanKeyboard();
v.clearFocus();
spinnerkontak1.requestFocus();
spinnerkontak1.performClick();
}
return true;
}
});
spinnerkontak1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String jeniskontak1 = spinnerkontak1.getSelectedItem().toString();
if(jeniskontak1.equals("--")){
edkontak1.setText("");
edkontak1.setEnabled(false);
tkontak2.setVisibility(View.GONE);
tkontak3.setVisibility(View.GONE);
tkontak4.setVisibility(View.GONE);
tkontak5.setVisibility(View.GONE);
}
else{
edkontak1.setEnabled(true);
tkontak2.setVisibility(View.VISIBLE);
spinnerkontak1.setFocusable(true);
spinnerkontak1.setFocusableInTouchMode(true);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
private void sembunyikanKeyboard() {
InputMethodManager inputmanaget = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputmanaget.hideSoftInputFromInputMethod(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
Thanks in advance.
I think you should implement request focus method edkontak1.requestFocus();
What you have done is correct. But you have to add this line too.
spinnerkontak1.setFocusable(true);
I am working on my project where I have a listView and each item is a LinaerLayout that has a TextView with Linkify hyperlink.
So, when I press the an item in the List view, it opens a dialog, which is fine.
When I press the linked text in the listView, it opens a dialog, which is fine.
PROBLEM: When I LONG-PRESS the linked text in the Listview, it opens a dialog AND an activity of the given link at the same time! In this case, I only want it to open the dialog only.
In other words, I want to ignore Linkify's hyperlink on Long press.
Does anyone know how I can do this?
I don't know where to apply LongPress attributs... Thanks in advance.
FYI, I tried the following but doesn't work.
public class URLSpanNoUnderline extends URLSpan implements OnLongClickListener {
public URLSpanNoUnderline(String url) {
super(url);
}
#Override
public void updateDrawState(TextPaint textPaint) {
super.updateDrawState(textPaint);
textPaint.setUnderlineText(false);
}
#Override
public void onClick(View v) {}
#Override
public boolean onLongClick(View v) {
Log.d("log", "lonnnnnnnnnnnnnnnng click");
return false;
}
}
you need a longClick mark,set it when in textview longclicklistener,and in touchlistener,when action equals MotionEvent.ACTION_UP and longClick is true,return true。
textview.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
isLongClick= true;
return false;
}
});
textview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP && isLongClick){
isLongClick= false;
return true;
}
if(event.getAction() == MotionEvent.ACTION_DOWN){
isLongClick= false;
}
return v.onTouchEvent(event);
}
});
this problem happend in some phone.
I created an Android application with a Spinner and a TextView. I want to display the selected item from the Spinner's drop down list in the TextView. I implemented the Spinner in the onCreate method so when I'm running the program, it shows a value in the TextView (before selecting an item from the drop down list).
I want to show the value in the TextView only after selecting an item from the drop down list. How do I do this?
Here is my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class GPACal01Activity extends Activity implements OnItemSelectedListener {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner spinner = (Spinner) findViewById(R.id.noOfSubjects);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.noofsubjects_array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
TextView textView = (TextView) findViewById(R.id.textView1);
String str = (String) parent.getItemAtPosition(pos);
textView.setText(str);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
spinner.setOnItemSelectedListener(this); // Will call onItemSelected() Listener.
So first time handle this with any Integer value
Example:
Initially Take int check = 0;
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
if(++check > 1) {
TextView textView = (TextView) findViewById(R.id.textView1);
String str = (String) parent.getItemAtPosition(pos);
textView.setText(str);
}
}
You can do it with boolean value and also by checking current and previous positions. See here
Just put this line before setting the OnItemSelectedListener
spinner.setSelection(0,false)
This works because setSelection(int, boolean) calls setSelectionInt() internally so that when the listener is added, the item is already selected.
Beware that setSelection(int) won't work, because it calls setNextSelectedPositionInt() internally.
Beginning with API level 3 you can use onUserInteraction() on an Activity with a boolean to determine if the user is interacting with the device.
http://developer.android.com/reference/android/app/Activity.html#onUserInteraction()
#Override
public void onUserInteraction() {
super.onUserInteraction();
userIsInteracting = true;
}
As a field on the Activity I have:
private boolean userIsInteracting;
Finally, my spinner:
mSpinnerView.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view, int position, long arg3) {
spinnerAdapter.setmPreviousSelectedIndex(position);
if (userIsInteracting) {
updateGUI();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
As you come and go through the activity the boolean is reset to false. Works like a charm.
This worked for me
Spinner's initialization in Android is problematic sometimes
the above problem was solved by this pattern.
Spinner.setAdapter();
Spinner.setSelected(false); // must
Spinner.setSelection(0,true); //must
Spinner.setonItemSelectedListener(this);
Setting adapter should be first part and onItemSelectedListener(this) will be last when initializing a spinner. By the pattern above my OnItemSelected() is not called during initialization of spinner
haha...I have the same question.
When initViews() just do like this.The sequence is the key, listener is the last. Good Luck !
spinner.setAdapter(adapter);
spinner.setSelection(position);
spinner.setOnItemSelectedListener(listener);
To avoid calling spinner.setOnItemSelectedListener() during initialization
spinner.setSelection(Adapter.NO_SELECTION, true); //Add this line before setting listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
My solution:
protected boolean inhibit_spinner = true;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
if (inhibit_spinner) {
inhibit_spinner = false;
}else {
if (getDataTask != null) getDataTask.cancel(true);
updateData();
}
}
You can do this by this way:
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//set the text of TextView
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
yourSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
yourSpinner.setOnItemSelectedListener(listener);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
At first I create a listener and attributed to a variable callback; then i create a second listener anonymous and when this is called at a first time, this change the listener
=]
The user interaction flag can then be set to true in the onTouch method and reset in onItemSelected() once the selection change has been handled. I prefer this solution because the user interaction flag is handled exclusively for the spinner, and not for other views in the activity that may affect the desired behavior.
In code:
Create your listener for the spinner:
public class SpinnerInteractionListener implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
boolean userSelect = false;
#Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (userSelect) {
userSelect = false;
// Your selection handling code here
}
}
}
Add the listener to the spinner as both an OnItemSelectedListener and an OnTouchListener:
SpinnerInteractionListener listener = new SpinnerInteractionListener();
mSpinnerView.setOnTouchListener(listener);
mSpinnerView.setOnItemSelectedListener(listener);
create a boolean field
private boolean inispinner;
inside oncreate of the activity
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!inispinner) {
inispinner = true;
return;
}
//do your work here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Similar simple solution that enables multiple spinners is to put the AdapterView in a collection - in the Activities superclass - on first execution of onItemSelected(...) Then check to see if the AdapterView is in the collection before executing it. This enables one set of methods in the superclass and supports multiple AdapterViews and therefor multiple spinners.
Superclass ...
private Collection<AdapterView> AdapterViewCollection = new ArrayList<AdapterView>();
protected boolean firstTimeThrough(AdapterView parent) {
boolean firstTimeThrough = ! AdapterViewCollection.contains(parent);
if (firstTimeThrough) {
AdapterViewCollection.add(parent);
}
return firstTimeThrough;
}
Subclass ...
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (! firstTimeThrough(parent)) {
String value = safeString(parent.getItemAtPosition(pos).toString());
String extraMessage = EXTRA_MESSAGE;
Intent sharedPreferencesDisplayIntent = new Intent(SharedPreferencesSelectionActivity.this,SharedPreferencesDisplayActivity.class);
sharedPreferencesDisplayIntent.putExtra(extraMessage,value);
startActivity(sharedPreferencesDisplayIntent);
}
// don't execute the above code if its the first time through
// do to onItemSelected being called during view initialization.
}
Try this
spinner.postDelayed(new Runnable() {
#Override
public void run() {
addListeners();
}
}, 1000);.o
Code
spinner.setOnTouchListener(new View.OnTouchListener() {
#Override public boolean onTouch(View view, MotionEvent motionEvent) { isSpinnerTouch=true; return false; }});
holder.spinner_from.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int slot_position, long l) {
if(isSpinnerTouch)
{
Log.d("spinner_from", "spinner_from");
spinnerItemClickListener.onSpinnerItemClickListener(position, slot_position, AppConstant.FROM_SLOT_ONCLICK_CODE);
}
else {
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
You could achieve it by setOnTouchListener first then setOnItemSelectedListener in onTouch
#Override
public boolean onTouch(final View view, final MotionEvent event) {
view.setOnItemSelectedListener(this)
return false;
}
This worked for me:
spinner.setSelection(0, false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
spinner.setOnItemSelectedListener(listener);
}, 500);
Based on Abhi's answer i made this simple listener
class SpinnerListener constructor(private val onItemSelected: (position: Int) -> Unit) : AdapterView.OnItemSelectedListener {
private var selectionCount = 0
override fun onNothingSelected(parent: AdapterView<*>?) {
//no op
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (selectionCount++ > 1) {
onItemSelected(position)
}
}
}
You can create custom OnItemSelectedListener like this. I've taken val check=0 and in onItemSelected() method i did check if its count is 0? If 0 means its called during initialization. So simply ignore it.
I've also called separate abstract method called onUserItemSelected() I'll call this method is check > 0. This works perfectly fine for me.
abstract class MySpinnerItemSelectionListener : AdapterView.OnItemSelectedListener {
abstract fun onUserItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long)
private var check = 0
override fun onItemSelected(
parent: AdapterView<*>?,
view: View,
position: Int,
id: Long
) {
if (++check > 1) {
onUserItemSelected(parent, view, position, id)
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
And then you can set listener like this.
mySpinner.onItemSelectedListener = object : MySpinnerItemSelectionListener() {
override fun onUserItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
//your user selection spinner code goes here
}
}
Had the same problem and this works for me:
I have 2 spinners and I update them during init and during interactions with other controls or after getting data from the server.
Here is my template:
public class MyClass extends <Activity/Fragment/Whatever> implements Spinner.OnItemSelectedListener {
private void removeSpinnersListeners() {
spn1.setOnItemSelectedListener(null);
spn2.setOnItemSelectedListener(null);
}
private void setSpinnersListeners() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
spn1.setOnItemSelectedListener(MyClass.this);
spn2.setOnItemSelectedListener(MyClass.this);
}
}, 1);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Your code here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
When the class is initiating use setSpinnersListeners() instead of directly setting the listener.
The Runnable will prevent the spinner from firing onItemSelected right after the you set their values.
If you need to update the spinner (after a server call etc.) use removeSpinnersListeners() right before your update lines, and setSpinnersListeners() right after the update lines. This will prevent onItemSelected from firing after the update.
For me, Abhi's solution works great up to Api level 27.
But it seems that from Api level 28 and upwards, onItemSelected() is not called when listener is set, which means onItemSelected() is never called.
Therefore, I added a short if-statement to check Api level:
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,long id) {
if(Build.VERSION.SDK_INT >= 28){ //onItemSelected() doesn't seem to be called when listener is set on Api 28+
check = 1;
}
if(++check > 1) {
//Do your action here
}
}
I think that's quite weird and I'm not sure wether others also have this problem, but in my case it worked well.
I placed a TextView on top of the Spinner, same size and background as the Spinner, so that I would have more control over what it looked like before the user clicks on it. With the TextView there, I could also use the TextView to flag when the user has started interacting.
My Kotlin code looks something like this:
private var mySpinnerHasBeenTapped = false
private fun initializeMySpinner() {
my_hint_text_view.setOnClickListener {
mySpinnerHasBeenTapped = true //turn flag to true
my_spinner.performClick() //call spinner click
}
//Basic spinner setup stuff
val myList = listOf("Leonardo", "Michelangelo", "Rafael", "Donatello")
val dataAdapter: ArrayAdapter<String> = ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, myList)
my_spinner.adapter = dataAdapter
my_spinner.onItemSelectedListener = object : OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
if (mySpinnerHasBeenTapped) { //code below will only run after the user has clicked
my_hint_text_view.visibility = View.GONE //once an item has been selected, hide the textView
//Perform action here
}
}
override fun onNothingSelected(parent: AdapterView<*>?) {
//Do nothing
}
}
}
Layout file looks something like this, with the important part being that the Spinner and TextView share the same width, height, and margins:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Spinner
android:id="#+id/my_spinner"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="#drawable/bg_for_spinners"
android:paddingStart="8dp"
android:paddingEnd="30dp"
android:singleLine="true" />
<TextView
android:id="#+id/my_hint_text_view"
android:layout_width="match_parent"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:background="#drawable/bg_for_spinners"
android:paddingStart="8dp"
android:paddingEnd="30dp"
android:singleLine="true"
android:gravity="center_vertical"
android:text="*Select A Turtle"
android:textColor="#color/green_ooze"
android:textSize="16sp" />
</FrameLayout>
I'm sure the other solutions work where you ignore the first onItemSelected call, but I really don't like the idea of assuming it will always be called.
I solved this problem like this:
In the activity lifecycle method whose name is onResume():
I added Spinner.setOnItemSelectedListener(this);
As a result, when our spinner call onclick method in the initialize, it does not work.
onResume method starts working when the finished Android page is displayed.