Add Onclick Listener to Predefined Button

add onclick listener to predefined button?

You just need something like this:

Button buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
});

How to add an onclick Event Listener to a created button element in Javascript?

So what you can do is append to the parent using HTML DOM without creating elemnt.

(parentElemnt).innerHTML += `<button value="addb" id="addb" onclick="subWords">Add Words!</button>`;

The += will append what is inside `` ... Instead of creating and appending and then giving the values, you can do it one line. Select the parent element using DOM and then substitute inside

(parentElement)

.

Check if this works out and good luck.
I am sorry for not including the code of the best practices. If you could share your entire code I would be happy to check on how to fix without appending to an element.

Lasal.

Android programmatically created button onClick from class

You cannot assign a Context from a field. You probably "can't assign a right", because you're actually getting a nullpointerexception and editing the wrong location. That being said, getApplicationContext() isn't needed.

Also, might I suggest that you return the content layout rather than casting the context to an Activity?

public Navigation nav;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
nav = new Navigation(this);
setContentView(nav.mainMenu());

}

@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btnGame:
nav.game();
break;
}
}

At first glance, I see that you never set a click listener on the button, so you should probably do that.

For example

Context mContext;
View.OnClickListener mClickListener;

Navigation(Context context) {
this.mContext = context;
if (context instanceof View.OnClickListener) {
this.mClickListener = (View.OnClickListener) context ;
}
}

Now use this

if (mClickListener!=null) {
button.setOnClickListener(mClickListener);
}

I'm also not sure what I should be expecting from v.getId() in MainActivity.java R.id.btnGame?

The ID doesn't match the variable name. Without explicitly giving the button an ID, it'll be -1

How to add onClick event to button using properties section in Android Studio

From properties in front of onClick add a method name say "showToast"

It will add the following line in that view in your xml

Example

<?xml version="1.0" encoding="utf-8"?>
<!-- layout elements -->
<Button android:id="@+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="showToast" //**THIS LINE**
/>
<!-- even more layout elements -->

Then in your java class (Activity) add a method with the same name

   public void showToast(View v) {
// does something
}

How to set on click listener for a custom button?

You seem to be setting another button as the listener for your original button, depending on what actions you hope to do in the listener, this can have unexpected behavior.

The easier solution would be to set itself as the listener, Whilst you've implemented View.onClicklistener in your MyButton, you haven't set that as the listener to itself. You'll need to do so in the constructor.

If you wish to support user set onClickListeners along with the MyButton listener, then you'll need to maintain a listener variable in your MyButton class which you can then explicitly call.

Finally, use your MyButton in your layout directly, instead of using Button as you currently seem to be doing.

Your final MyButton class should be something along the following lines,

public class MyButton extends androidx.appcompat.widget.AppCompatButton implements View.OnClickListener {

public MyButton(Context context) {
super(context);
init();
}

public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}

private void init() {
setOnClickListener(this);
}

private View.OnClickListener mUserOnClickListener;

@Override
public void setOnClickListener(@Nullable OnClickListener l) {
if (l == this) {
super.setOnClickListener(l);
} else {
mUserOnClickListener = l;
}
}

@Override
public void onClick(View v) {
//Your actions
Toast.makeText(getContext(), "MyButton clicked", Toast.LENGTH_SHORT).show();
if (mUserOnClickListener != null) {
mUserOnClickListener.onClick(v);
}
}
}

P.S - I'd also suggest you go through naming conventions for Java.

How to dynamically add listener to button on customAdapter in android

Add click listener on button of item in getView:
increment.setOnClickListener(this);
decrement.setOnClickListener(this);

then add tag of that object on these button in getView:
increment.setTag(no); // "no" is your cuttent object(mode)
decrement.setTag(no); // "no" is your cuttent object(mode)

Now implement Onclick method in adapter:

public void onClick(View v) {
switch(v.getId()) {
case R.id.pluse_signal:
No_Of_Emp_Pojo selectedItem = (No_Of_Emp_Pojo)v.getTag();
//now you can update this item in db or in any place.
break;
case R.id.minus_signal:
No_Of_Emp_Pojo selectedItem1 = (No_Of_Emp_Pojo)v.getTag();
//now you can update this item in db or in any place.
break;
}
}

And this click listnder will be called for every item of listview. And you can get model related to every item.

Dynamically append functionality to Button's onclicklistener Android

Since we don't no much about the background why you want to do so, it is hard to what is the best. If you want to have the original listener unchanged / untouched, you could use a decorator / wrapper pattern.

Wikipedia Decorator Pattern

In the concrete case this means, it is quite comparable to your Runnable approach, but you do not depend on another Interface. Everthing is handled via the View.OnClickListener, which has the following advantages:

  1. It is a generic approach with which you can even "extend" listeners to which you have no source access or which you do not want to modify.
  2. You can create the extension behaviour at runtime and you can extend already instantiated listeners (in contrast to the use of inheritance)
  3. The extensions do not have to know that they are extensions, they are just normal OnClickListeners. In your Runnable approach the extensions are "special" and for example they do not get the View paramter of the onClick method passed.

    public class OriginalOnClickListener implements View.OnClickListener{

    @Override
    public void onClick(View v) {
    Toast.makeText(MainActivity.this,"Original Click Listener",Toast.LENGTH_LONG).show();
    }
    }

    public class ExtensionOnClickListener implements View.OnClickListener{

    @Override
    public void onClick(View v) {
    Toast.makeText(MainActivity.this,"Extension Click Listener",Toast.LENGTH_LONG).show();
    }
    }

    public class DecoratorOnClickListener implements View.OnClickListener {

    private final List<View.OnClickListener> listeners = new ArrayList<>();

    public void add(View.OnClickListener l) {
    listeners.add(l);
    }

    @Override
    public void onClick(View v) {
    for(View.OnClickListener l : listeners){
    l.onClick(v);
    }
    }
    }

And the usage is like this:

    DecoratorOnClickListener dl = new DecoratorOnClickListener();

dl.add(new OriginalOnClickListener());
dl.add(new ExtensionOnClickListener());

editText.setOnClickListener(dl);

How to add the OnClickListener Object in Android?

first you have to create the listener,

View.OnClickListener mFan = new OnClickListener(){
public void onClick(View v)
{
}
};

and then that you have created an OnClickListener now set to your button.

button.setOnClickListener(mFan);

Button on click listener

You have three options:

common in 1,2) You need to assign an id to each of your buttons in the layout XML file

<Button android:id="@+id/my_button1"
..........
/>
<Button android:id="@+id/my_button2"
..........
/>

1) In the activity's onCreate() method after setContentView() you need to set a new OnClickListener for each button.

 public class MyActivity extends Activity  {
int a;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myButton1 = (Button) findViewById(R.id.my_button1);
Button myButton2 = (Button) findViewById(R.id.my_button2);

myButton1.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// Do what you want here
a = 1;
}
});

myButton2.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
// Do what you want here
a = 2;
}
});
}

2) As you see in the first approach, we need to make a new Object from the OnClickListener for each button. We can mix all that into one OnClickListener for performance and readability reasons.

public class MyActivity extends Activity implements View.OnClickListener {
int a;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myButton1 = (Button) findViewById(R.id.my_button1);
myButton1.setOnClickListener(this);
Button myButton2 = (Button) findViewById(R.id.my_button2);
myButton2.setOnClickListener(this);
}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.my_button_1:
a = 1;
break;
case R.id.my_button_2:
a = 2;
break;
}
}
...
}

3) You don't need to assign an id for this option you just need to assign the method name in the XML and then implement the same method in the activity with the exact same name but it must take a View object as an argument.

<Button 
...
android:onClick="button1Click" />

<Button
...
android:onClick="button2Click" />

and then in your activity just write the methods.

public class MyActivity extends Activity implements View.OnClickListener {
int a;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void button1Click(View v) {
a = 1;
}

public void button2Click(View v) {
a = 2;
}
}

That's all your options. I personally prefer number 2.

how to set onclicklistener for many programatically added views where are buttons

Note: the code below is untested, just giving you a hint.
Assuming you have some sort of plus button to add a new row and every single row has its own delete button.

On create method:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//no idea what is order_X_btn, but I assume that's delete row button
// if so then you don't need it here
//button = (Button) findViewById(R.id.order_X_btn);
orderTable = (TableLayout) findViewById(R.id.main_orders_table);
order = (TableRow) findViewById(R.id.main_orders_rows);
//final ViewGroup orders = (ViewGroup) orderTable;
plus = (TextView) findViewById(R.id.plus);
plus.setOnClickListener(this);
//this is not needed here either
//button.setOnClickListener(this);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
getSupportActionBar().hide();
//orderTable.addView(order);

}

Then onClick:

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.plus:
addOrder();
break;
}
}

Add order:

private void addOrder() {
last++;
final View extend = LayoutInflater.from(this).inflate(R.layout.order,null);
extend.setTag(orderTable.getChildAt(last));
Button deleteButton = (Button) extend.findViewById(R.id.order_X_btn);
deleteButton.setTag(extend);
// set anonymous on click listener which triggers deleteOrder method
deleteButton.setOnClickListener(v -> deleteOrder(v));
orderTable.addView(extend);

}

Delete order:

private void deleteOrder(View v) {
last--;

orderTable.removeView((View) v.getTag());

}

There might be some mistakes as I don't have IDE atm, but I hope you got the idea.



Related Topics



Leave a reply



Submit