RadioButton in android

 

Step 1: Create layout such as
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">

<RadioButton
android:id="@+id/rdi_ios"
android:layout_marginRight="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="iOs" />

<RadioButton
android:id="@+id/rdi_android"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android" />

</LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 2: Get control attribute of view on code java file
public class MainActivity extends AppCompatActivity {

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

RadioButton rdiButton = findViewById(R.id.rdi_ios);
rdiButton.setChecked(false);
rdiButton.setOnCheckedChangeListener((buttonView, isChecked) -> {
Toast.makeText(this, "RadioButton working", Toast.LENGTH_SHORT).show();
});
}
}

Step 3: Result 

Đăng nhận xét

Mới hơn Cũ hơn