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 voi...

问题:

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


回答1:

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

回答2:

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


回答3:

using

this

in the onclicklistener will reference the listener you should use

MainActivity.this or getActivity()
  • 发表于 2019-03-17 14:56
  • 阅读 ( 234 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除