Rafael F.
Rafael F.

Reputation: 415

findViewById return null using parameter of OnClick method of OnClickListener interface

my code:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    Button btn = (Button) findViewById(R.id.btn_ok);

    btn.setOnClickListener(new Click());

}

my class witch implements OnClickListener

but on method Click of "Click" class.. the parameter View v.. dont work. using method findViewById.. always return null :(

any help?

    public class Click implements View.OnClickListener
{       
    @Override
    public void onClick(View v) {       
        TextView view = (TextView) v.findViewById(R.id.resultado);
        EditText textoEdit = (EditText) v.findViewById(R.id.campo_texto);

        String texto = textoEdit.getText().toString();
        view.setText("Obrigado " + texto);  
    }
}

(sorry for my english)

Upvotes: 3

Views: 2258

Answers (2)

dcow
dcow

Reputation: 7975

A Button doesn't have any child views, thus no view will be found when you call findViewById. The View v parameter is the view that generated the touch event. If you want to talk to the TextView and EditText in your layout, you should find them in onCreate and store them as class members.

Try:

TextView mTexto;
EditText mTextoEdit;

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

    Button btn = (Button) findViewById(R.id.btn_ok);
    btn.setOnClickListener(new Click());

    mTexto= (TextView) findViewById(R.id.resultado);
    mTextoEdit = (EditText) findViewById(R.id.campo_texto);
}

And in your listener:

public class Click implements View.OnClickListener
{       
    @Override
    public void onClick(View v) {       
        String texto = mTextoEdit.getText();
        mTexto.setText("Obrigado " + texto);  
    }
}

Upvotes: 2

David
David

Reputation: 3418

The parameter View v references your button. That button view does not contain an element with R.id.resultado. Try v.getRootView().

Upvotes: 4

Related Questions