I have 40 textviews but I want to know which one was pressed so that it takes me to the desired Intent. How do I implement this ?
Implement onClickListener for all the TextViews. And handle the clicks according to TextView IDs in your listener. Its same as you handle onClick for a single textView.
In your listener use:
public void onClick(View view) {
switch(view.getId()) {
case R.id.textView1:
break;
case R.id.textView2:
break;
}
}
Adding an OnClickListener for all the views can be cumersome. The best way is probably a better way of laying these textView out. Probably a ListView or some implementation of RecyclerView.
But just as an answer to your question, make your class implement View.OnClickListener and check the id of the clicked View in the onClick method.
public class MainActivity extends Activity implements View.OnClickListener {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.textView1:
// code here
break;
case R.id.textView2:
//code here
break;
}
}
}
Related
Let's say that I have two ImageViews, and I want to know which one was clicked. How do I use getView() in this case? It's should be something like that
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
checkViewId();
switch(id){
case 1:
log.d -> ("id = 1");
}
break;
case 2:
log.d -> ("id = 2");
break;
return true;
}
How should I create this checkViewId method?
Make your activity/fragment implement the OnClickListener interface and add the onClick callback:
public class MainActivity extends Activity implements View.OnClickListener {
#Override
public void onClick(View v) {
}
}
When you’re binding the views, set the listener for all of them:
ImageView one = (ImageView) findViewById(R.id.one);
one.setOnClickListener(this);
ImageView two = (ImageView) findViewById(R.id.two);
two.setOnClickListener(this);
Inside the onClick method create your switch:
switch (v.getId()) {
case R.id.one:
// add your code
break;
case R.id.two:
// add your code
break;
default:
break;
}
I am designing a RecyclerView list. Each item of the Recyclerview contains a LinearLayout. This LinearLayout contains two views, the first one is an EditText and the second one is Button. When user taps on the button, it fires an onclick event. From onClick listener, I need to get the content of the EditText. I don't find a way to access the content of a sibling view when the user taps on another sibling view.
My question is not "how can I set on click listener to a button inside adapter". Most of the people answered how to set onClick listener to a button which is there inside the recyclerview item. My question is bit different, when I am inside onClick method which is fired from button, how will I access the edittext which is a sibling of button. Every item has one edittext, so when I click on a button how will I find the correct edittext?
For example, I have a recylerview of size 10. And each item of recyclerview contains a LinearLayout and inside linearlayout two item, one is an Edittext and the other one is a Button. when I tap on 7th items button, how will I get the text of 7th item's Edittext? I hope I have explained it well
Any help would be appreciated.
First of, you need two references: one to your EditText and one to your Button. You can get those in your ViewHolder. Next, you need an OnClickListener. The ViewHolder can conveniently also implement one but you could also use onBindViewHolder() for that.
Inside that OnClickListener you can filter out your id with a switch statement if you want to and then get the content of the EditText like this:
switch(viewId) {
case R.id.buttonId:
String text = editText.getText().toString();
// do something with that text
return true;
}
In case you implemented an OnClickListener in your ViewHolder you can then do this button.setOnClickListener(this); inside your ViewHolder to make sure onClick() is actually called when you click the button.
EDIT:
Here's some sample code that should work for your case. I'm implementing View.OnClickListener here as mentioned above.
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
EditText editText;
Button button;
public ViewHolder(View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.editText);
button = itemView.findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.button:
String text = editText.getText().toString();
break;
}
}
}
This is what it would look like if you were to do it in your onBindViewHolder() (in this case you would NOT implement the OnClickListener in your ViewHolder obviously):
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = holder.editText.getText().toString();
}
});
}
Step 1 :Make an abstract function in your adapter.
abstract void onButtonClicked(String text);
Step 2: Declare your adapter Abstract.
Step 3: Override the method (onButtonClicked(String text);) in your activity were you have instantiated the adapter.
Step 4: In your adapter inside the onClickListener for your button call the function :
onButtonClicked(editText.getText().toString());
and you'll get the string in your activity where you overrided the method.
You can use holder pattern for RecylcerView adapter. Then you can set click listener on your button and get the text from EditText.
public class SimpleViewHolder extends RecyclerView.ViewHolder {
private EditText simpleEditText;
private Button simpleButton;
public SimpleViewHolder(final View itemView) {
super(itemView);
simpleEditText = (EditText) itemView.findViewById(R.id.simple_edit_text);
simpleButton = (Button) itemView.findViewById(R.id.simple_button);
simpleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = simpleEditText.getText().toString()
}
});
}
}
You can do it inside your adapter which is being set on the recycler view.
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
}
}
And in the bindview holder you can access the views
public void onBindViewHolder(#NonNull final ImageAdapter.MyViewHolder holder, int position) {
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Your Code to access the edit text content
}
});
}
use a custom listener like this in the holder:
public class SimpleViewHolder extends RecyclerView.ViewHolder {
private EditText simpleEditText;
private Button simpleButton;
public SimpleViewHolder(final View itemView, final OnItemSelectedListener listener) {
super(itemView);
simpleEditText = (EditText) itemView.findViewById(R.id.simple_edit_text);
simpleButton = (Button) itemView.findViewById(R.id.simple_button);
simpleButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String text = simpleEditText.getText().toString();
if(listener != null) listener.onItemSelected(text);
}
});
}
public interface OnItemSelectedListener{
void onItemSelected(String value);
}
}
Simply Use Your ViewHolder. It contains all the children you want. Implement the code inside your adapter where each item is inflated. Here is an example.
//inside the onBindViewHolder
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = viewHolder.editText.getText().toString();
Log.d("output", text);
}
});
If you are using FirebaseUI Implement this inside the populateViewHolder for older version and onBindViewHolder for the later versions.
People put -1 when they don't know the answer or when they do not understand question. So funny!! In onclick I took parent(getParent()) from the view and accessed the second child of the parent. With that I am able to access the content of the sibling.
` public void onClick(View v) {
for(int i = 0;i<parent.getChildCount();i++){
if(parent.getChildAt(i)instanceof EditText){
passwordView = (EditText)parent.getChildAt(i);
}
}
}`
Total Android beginner here...
I have an Activity with an OnClick Listener as in this example: Multiple Buttons `OnClickListener()` android
And now I'm setting up a listener on Floating Action Button in a different activity. What I'm not sure about is whether it is possible to use that same listener, or does each class have to have it's own?
ACTIVITY #1 // a regular activity
public class Requests extends AppCompatActivity implements View.OnClickListener {...}
ACTIVITY #2 // A RecyclerView, CardView type activity
public static class MyViewHolder extends RecyclerView.ViewHolder {...}
I'd really like to have one Listener to handle the cardview click events, as well as the Floating Action Button.
in general you can use the same listener for multiple buttons. if they are in different activities , you can write a seperate class that implements View.OnClickListener . Like this:
public class MyButtonListener implements View.OnClickListener {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.oneButton:
// do your code
break;
case R.id.twoButton:
// do your code
break;
case R.id.threeButton:
// do your code
break;// default method for handling onClick Events..
}
}
Then you just have to set your button listener like button.setOnClicklistener(new MyOnClickListener());
If your buttons are all doing the same action, you wont need the switch-case block.
Creating a seperate listener class is not a bad idea at all BUT: you should try to implement one for each activty to keep an overview over your button actions.
You can use below code snipet mentioned in the link below
Handle click item in Recycleview
In that onClick and onItemClick Override listener you can implement both Floating Action Button and cardview click events position wise
To perform same operation on click event of different view or viewGroup implement an anonymous class for OnClickListener as
View.OnClickListener mOnClickListener= new View.OnClickListener() {
#Override public void onClick(View v) { /*do your code */ }};
or call it in your activity as
mbutton.setOnClickListener(mOnClickListener);
mcardView.setOnClickListener(mOnClickListener);
Hello I have a trouble with OnClickListener
View.OnClickListener listener= new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(Conversations.this, "click on MSG",
Toast.LENGTH_SHORT).show();
}
};
========================================================================
I Need put this listener into Fragment which will parceable.
I not parceableing listener but after readvalue is null and when click app crasher because it's reference on null object.
now I need find some methods which can use for save and read object (View.OnClickListener) if parceable or something similar.
Without this I need rebuild my project :(
Please Help me.
Thanks
_______________________________________________________--
I haven't have fragment in fragment I want all fragment put into "extra" and in other activity read from extra..
Intent i= new Intent(Conversations.this,MessagesSingleFragmentActivity.class); i.putExtra("Fragment1", (Parcelable) recycleMessage); startActivity(i);
and in other activity have
Intent extras = getIntent(); Fragment fragment = (Fragment) extras.getParcelableExtra("Fragment1"); fm.beginTransaction().replace(R.id.fragment_container, fragment).commit();
No you cannot pass OnClickListener as Parcelable but , if you want to observe click from one fragment to another , then you have to implement the onclick in second fragment.
FragA.java:// who have onClickListener
Runnable run;
public void setClick(Runnable run){
this.run = run;
}
view.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// do something in onclick
if(run!=null){run.run();}
}
});
FragB.java:
((FragA)getParentFragment()).setClick(
new Runnable() {
#Override
public void run() {
// do something in other fragment
}
}
)
Updated:
If you want to perform something onClick of ActivityA on ActivityB , then EventBus are best options for that use Otto or EventBus by GreenBot
It is recommended to interact between fragments via Activity.. or more generally by interface which Activity conforms to.
One more thing: If you have common functionality in both fragments, maybe it is better to extract it to Activity?
What I'm trying to do is simple, I have a spinner with a few items, edittext and a button. I want to be able to select a certain item with a spinner and then type a certain value to edittext and then click a button. According to which spinner item I have selected earlier a textview will then change in the activity.
public void submitButtonClick (View submit){
Spinner s1 = (Spinner)findViewById(R.id.spinner1);
Button b1 = (Button)findViewById(R.id.button2);
if (b1.performClick())
{
switch (){
}
}
}
This is what I came up with so far, if I click button b1, the following switch statement should start (in case item 1 is selected, do a certain thing, etc.) but I don't know how to achieve this. If someone could help I would appreciate it. Thank you
This is what I have so far:
public void submit (View v){
Button b1 = (Button)findViewById(R.id.button2);
final Spinner s1 = (Spinner)findViewById(R.id.spinner1);
final Context context = this;
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = s1.getSelectedItemPosition();
switch (position){
case 0:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Warning");
alertDialogBuilder.setMessage("Please choose an item from the list");
alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Bifrost.this.finish();
}
});
AlertDialog spinnerError = alertDialogBuilder.create();
spinnerError.show();
break;
case 1:
break;
}
}
});
}
The code gives no errors and app starts normally but when I select the first item and then click the button nothing happens. Did I do something wrong creating the dialog?
You first need to set an onClickListener to your button, and in this you need to get the selected item of the spinner.
b1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
int position = s1.getSelectedItemPosition();
switch(position){
case 0: //first item
break;
case 1: //second item
break;
}
}
});
You can use one of the following methods to get the spinner's selected item.
spinner.getSelectedItem()
spinner.getSelectedItemPosition()
Which one you use, has to do with how you load items into your spinner.
Follow this link for more info on those methods.
You can do something like this. you need to set a onClickListener to the button. when the button is clicked then the onClick method will be called. At that method check the selected item of the spinner.. Forexmple
Spinner s1 = (Spinner)findViewById(R.id.spinner1);
Button b1 = (Button)findViewById(R.id.button2);
b1.setOnclickListener(new onClickListener(){
public void onCLick(View v){
switch(s1.getSelectedItemPosition()){
case 0:
// do something
`enter code here`break
..........
}
}
}
);
I just tried to give a conceptual idea the code is not exact , but this is how you should do it. So my suggestion is before implementing this leanr the basic features of buttons, spinners, onCLickListeners.
You can assign a listener to your spinner.
s1.setOnItemSelectedListener(new OnItemSelectedListener() {
// will run every time the user select an item from your spinner
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// change your textView here, base on position (index of item selected in spinner)
if (position == 0) {
// user selected the first item in spinner
}
else if (position == 1) {
// user selected the second item in spinner
}
// and so on...
}
});
After that, you can assign another listener (similar way as the code above - anonymous inner class, anonymous declaration and initialization) for your button. It will also have to override onClick etc etc. There are lots of resources online regarding all of this.
Hope this helps!