Home > database >  Android studio button has no onclick option error message box
Android studio button has no onclick option error message box

Time:08-03

I'm currently learning to make apps in android studio. When I drag a button object into the activity_main.xml,it does not show me the "onclick" option under the "Declare Attributes".

The only error I'm getting is :

Couldn't resolve resource @color/teal_200 I dont think it has anything to do with my problem but still...

Any help would be appriciated,thank you!

CodePudding user response:

Add it via xml.

You'll find your button in there, declared like this:

<Button
    android:id="@ id/button"
    android:onClick="doSomething"
    ... />

Nevertheless, it's better style to get the button by id and apply an OnClickListener:

Button button = findViewById(R.id.button);
button.setOnClickListener(() -> {
    System.out.println("Clicked");
});

The color-error is caused by a missing color in res/values/colors.xml.

You'll have to add your color there like this:

<resources>
    <color name="errorRed">#FF0033</color>
</resources>

CodePudding user response:

make sure for when declaring color in your xml file you use

android:textcolor="@color/white" // for text color android:backgroundTint="@color/black" // for button background color

also in your activitymain.java I find it easier declaring your onclicks there

public class MainActivity extends AppCompatActivity {
Button buttonnamegoeshere;



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



}
buttonnamegoeshere.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //button code goes hereenter code here
    }
});

}

Hope this helps!

  • Related