-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<RadioGroup
android:id="@+id/radioGroupLanguages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:id="@+id/radioJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java" />
<RadioButton
android:id="@+id/radioKotlin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Kotlin" />
<RadioButton
android:id="@+id/radioSwift"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Swift" />
<RadioButton
android:id="@+id/radioPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Python" />
</RadioGroup>
<Button
android:id="@+id/btnShowSelection"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selection" />
</LinearLayout>
2. Create the MainActivity.java:
-
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private RadioGroup radioGroupLanguages;
private Button btnShowSelection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroupLanguages = findViewById(R.id.radioGroupLanguages);
btnShowSelection = findViewById(R.id.btnShowSelection);
btnShowSelection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showSelectedLanguage();
}
});
}
private void showSelectedLanguage() {
int ButtonId=radioGroupLanguages.getCheckedRadioButtonId();
if (selectedRadioButtonId != -1) {
RadioButton selectedRadioButton = findViewById(ButtonId);
String selectedLanguage = selectedRadioButton.getText().toString();
Toast.makeText(this,"Selected Language:"+selectedLanguage,Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Please select a programming language",Toast.LENGTH_SHORT).show();
}
}
}
No comments:
Post a Comment