Button Widget in Android Tutorial
Explanation:
Button is a widget under Buttons section which is used to execute specific code.
Example:
XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="173dp"
android:text="Button"
android:textStyle="bold"/>
</RelativeLayout>
Java File:
package com.example.android.sampleproject;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button b1;
private int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (i) {
case 0:
b1.setBackgroundColor(Color.BLUE);
i=1;
break;
case 1:
b1.setBackgroundColor(Color.RED);
i=0;
}
}
});
{
}
}
}
Before Click:
| After First Click:
| After Second Click:
|