-1

I am new to android and i am trying to change the text by clicking button but i am getting the error "can not resolve setOnClickListener" on third line.how can i resolve this?

  Button b=(Button)findViewById(R.id.button);
        b.setOnClickListener(
                new Button.setOnClickListener(){   //error in this line
                    public void onclick(View v){
                        TextView t=(TextView)findViewById(R.id.textView2);
                        t.setText("text changed!");
                    }
                }
        );
Abdul Rafay
  • 102
  • 2
  • 10
  • Possible duplicate of [Button OnClickListener not working](http://stackoverflow.com/questions/17335135/button-onclicklistener-not-working) – Vucko May 26 '16 at 16:16

3 Answers3

4

You have to use View

Button b=(Button)findViewById(R.id.button);
b.setOnClickListener(View.OnClickListener() {
   @Override
   public void onClick(View v) {
      TextView t=(TextView)findViewById(R.id.textView2);
      t.setText("text changed!");
  }
});
Deepak Goyal
  • 4,747
  • 2
  • 21
  • 46
2

Can you try like :

TextView t;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.yourlayout);
   t=(TextView)findViewById(R.id.textView2);
   b=(Button)findViewById(R.id.button);
   b.setOnClickListener(View.OnClickListener() {
        @Override
        public void onClick(View v) {
        t.setText("text changed!");
        }
   });
}

Also can you post your Xml too, for reference

Yasin Kaçmaz
  • 6,573
  • 5
  • 40
  • 58
2

When you want to ser a click listener in a Button, you should use setOnClickListener like you did but the argument must be an instance of Button.OnClickListener(), so you have to use new to create that instance. Beacuase Button.OnClickListener is an interface, you also have to implement public void onClick(View v) like you did.

Please, try this:

Button b=(Button)findViewById(R.id.button);
b.setOnClickListener(new Button.OnClickListener() {
    @Override
    public void onClick(View v) {
        TextView t=(TextView)findViewById(R.id.textView2);
        t.setText("text changed!");
    }
});
Pablo
  • 2,581
  • 3
  • 16
  • 31