-2

I make a Button and I want to make onClick method in XML

    <Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    android:id="@+id/button2"
    android:onClick="maysara"
    android:layout_alignParentTop="true"
    android:layout_alignLeft="@+id/button"
    android:layout_alignStart="@+id/button"
    android:layout_marginTop="63dp" />

Then I go to Java code to make the method "maysara"

public class MainActivity extends AppCompatActivity {

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


}

public void maysara(View v){
**if(v.getId()==findViewById(R.id.button2))**
    Toast.makeText(this,"button2",Toast.LENGTH_SHORT).show();}}

But I got an error in if statement >>> I really dont know why @?!

maysara
  • 5,873
  • 2
  • 23
  • 34

3 Answers3

0

Just use like this

public void maysara(View v){
 Toast.makeText(this,"button2",Toast.LENGTH_SHORT).show();
}

It help you.

Sanwal Singh
  • 1,765
  • 3
  • 17
  • 35
0

Check the return type of findViewById() which is a view and you are comparing with v.getId() which is id. You should not compare this.

public View findViewById (int id)

Shriram
  • 4,343
  • 8
  • 37
  • 64
0

I know this has an answer, but I thought I'd add one.

You are declaring

android:onClick="maysara"

as the onClick method in your xml for this button. There is no need to do a check on which button is clicking, as you have explicitly defined this in your xml.

So within your mayasara method, you only need to show what you want to do, not a check on the button clicking.

public void maysara(View v){


<Button
    android:id="@+id/button1"
    android:onClick="maysara"


<Button
    android:id="@+id/button2"
    android:onClick="maysara"

A switch statement is a much better option, as you do not need to check for the value of R.id.button2 as you have in your if statement. Checking those values for this type of function is a clumsy way of programming.

public void maysara(View v){
    switch(v.getId()) {
       case R.id.button1:
        // to do
       break;
       case R.id.button2:
        // to do
       break;