ShayW
ShayW

Reputation: 23

What should be the context parameter for ContextCompat.getDrawable( )?

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

Answers (3)

Boken
Boken

Reputation: 5445

If you are in class named MainActivity you can use:

In Kotlin:

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();
}

In Java:

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

Okeme Christian
Okeme Christian

Reputation: 312

using

this

in the onclicklistener will reference the listener you should use

MainActivity.this or getActivity()

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1006829

You can use v.getContext() to get the Context associated with that View.

Upvotes: 1

Related Questions