Reputation: 23
I use it in setOnClickListeneraccording to an another post here
like this :
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
start.setBackground(ContextCompat.getDrawable( this,R.drawable.buttonstop));
parameter this is wrong Thanks
Upvotes: 1
Views: 170
Reputation: 5445
If you are in class named MainActivity
you can use:
this@MainActivity
e.g.
button.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
Toast.makeText(this@MainActivity, "Hello!", Toast.LENGTH_SHORT).show();
}
})
// Or in shorter way:
frame_layout.setOnClickListener {
Toast.makeText(this@MainActivity, "Hello!", Toast.LENGTH_SHORT).show();
}
MainActivity.this
e.g.
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(A.this, "Hello!", Toast.LENGTH_SHORT).show();
}
});
// Or in shorter way:
button.setOnClickListener(v -> Toast.makeText(MainActivity.this, "Hello!", Toast.LENGTH_SHORT).show());
Upvotes: 0
Reputation: 312
using
this
in the onclicklistener will reference the listener you should use
MainActivity.this or getActivity()
Upvotes: 0
Reputation: 1006829
You can use v.getContext()
to get the Context
associated with that View
.
Upvotes: 1