Android data binding, Select value of RadioGroup when click button submit - java

I have a RadioGroup consisting of 2 choices and a button, After I press that button I want to get the value and based on that value I want to perform different actions:
<RadioGroup
android:id="#+id/rg_select"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toBottomOf="#+id/tv_title">
<RadioButton
android:id="#+id/rb_a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawableStart="#drawable/ic_mo_512dp"
android:drawablePadding="20dp"
android:paddingStart="10dp"
android:paddingEnd="0dp"
android:text="Visual Advance" />
<RadioButton
android:id="#+id/rb_b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:drawablePadding="20dp"
android:text="Visual basic" />
</RadioGroup>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click"
onSingleClick="#{() -> onClickListener.getRadioButton()}"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rg_select">
fun getRadioButton() {
val result = rg_select.checkedRadioButtonId
when (genderId) {
R.id.rb_a -> {
Toast.makeText(context, "KKSKSK", Toast.LENGTH_LONG).show()
}
R.id.rb_b -> {
Toast.makeText(context, "KKSKSK", Toast.LENGTH_LONG).show()
}
}
}
But my above code is not suitable for databinding so can anyone help me to solve this problem?

Can't see any obstacle for it. Just handle two actions separately, when radio button is checked "android:checked="#{viewModel.selectedRG.equals(RG.A)}", when button pressed onSingleClick="#{viewModel.performSomeAction()}". So in this case when performSomeAction() will be invoked RG type can be taken from "selectedRG".
If smth missed, let me know.

Related

How to implement a start/stop "button" in Android

My goal is to have a CardView that when is clicked, it goes from Start -> Stop and vice versa when clicked again. Inside the CardView I have two TextView which I would like to alter when it's clicked. The functionality behind this, would be to start a foreground service and stop it accordingly.
What I have in mind for the layout xml:
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:id="#+id/cardStartStop">
<TextView
android:id="#+id/txtCardStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/card_start"
app:drawableTopCompat="#drawable/ic_start_black_24dp" />
<TextView
android:id="#+id/txtCardStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:text="#string/card_stop"
app:drawableTopCompat="#drawable/ic_stop_circle_black_24dp" />
</androidx.cardview.widget.CardView>
</GridLayout>
Then I thought to programmatically change the visibility of each TextView and persist its state using SharedPreferences when closing and re-opening app. My question is more at a design level, is there a better way to achieve this or I'm pointing in the right direction?
Add one TextView and setOnClickListener
XML File
<androidx.cardview.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Start"
android:id="#+id/text_start_stop"
/>
</androidx.cardview.widget.CardView>
Class
private TextView tStartStop;
Boolean flag = true;
ClickEvent
tStartStop = findViewById(R.id.text_start_stop);
tStartStop.setOnClickListener(view -> {
if (flag) {
flag = false;
tStartStop.setText("Start");
} else {
flag = true;
tStartStop.setText("Stop");
}
});

How to get value of material dialog box input field in Android?

I have a material alert dialog box like this:
Here is the java code for the dialog box:
public void openAddNoteDialog() {
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(MainActivity.this, R.style.dialogBoxTheme);
builder.setTitle("Add note");
builder.setBackground(getResources().getDrawable(R.drawable.dialog_box, null));
builder.setIcon(R.drawable.ic_add_note);
builder.setView(R.layout.addnote_dialog);
builder.setPositiveButton("Add", ((dialogInterface, i) -> handleAddNote()));
builder.setNegativeButton("Cancel", (dialogInterface, i) -> dialogInterface.dismiss());
builder.show();
}
And here is the layout that is in the dialog box:
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/notenameFLD"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="260dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_marginTop="25dp"
android:hint="#string/notename"
android:textColorHint="#color/white"
app:boxStrokeColor="#color/white"
app:counterEnabled="true"
app:counterMaxLength="20"
app:counterTextColor="#color/white"
app:helperTextTextColor="#color/white"
app:hintTextColor="#color/white">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/notenameEDITFLD"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/opensans_regular"
android:maxLength="20"
android:textColor="#color/white"
android:textSize="20sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/notecontentFLD"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="260dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:layout_marginBottom="25dp"
android:hint="#string/notecontent"
android:textColorHint="#color/white"
app:boxStrokeColor="#color/white"
app:counterEnabled="true"
app:counterMaxLength="250"
app:counterTextColor="#color/white"
app:helperTextTextColor="#color/white"
app:hintTextColor="#color/white">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/notecontentEDITFLD"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="#font/opensans_regular"
android:maxLength="250"
android:textColor="#color/white"
android:textSize="20sp" />
</com.google.android.material.textfield.TextInputLayout>
Now, I'm trying to get the value of these input fields in other function called handleAddNote().
final TextInputEditText noteNameFLD = findViewById(R.id.notenameEDITFLD);
final TextInputEditText noteContentFLD = findViewById(R.id.notecontentEDITFLD);
The problem is, when I'm trying to get the values of these input fields as strings, they return nothing. What is the problem here? Is this because the findViewById() can't find the fields as they are inside of the alert dialog box and not in the actual activity?
Ps. sorry if this is confusing, I can add more info if needed.
Is this because the findViewById() can't find the fields as they are
inside of the alert dialog box and not in the actual activity?
Yes, you are correct :) you need to get them on the view you set to your dialogBuilder. Change the way you set your dialog view to:
final View dialogView = LayoutInflater.from(context).inflate(R.layout. addnote_dialog, null);
alertDialogBuilder.setView(dialogView);
Then, you can find the views using dialogView.findViewById().

How can I add different ids to buttons recyclerview

My project is based on a recycler view. The layout of each elements is this :
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp">
<ImageView
android:id="#+id/imgview"
android:layout_width="50dp"
android:layout_height="50dp"
android:padding="2dp" />
<TextView
android:id="#+id/txtview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="51dp"
android:layout_marginTop="1dp"
android:text="Line 1"
android:textColor="#android:color/black"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/txtview2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="52dp"
android:layout_marginTop="29dp"
android:layout_marginBottom="1dp"
android:text="Line 2"
android:textSize="15sp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="3dp"
android:layout_marginEnd="3dp"
android:text="Voir plus" />
</RelativeLayout>
And I edit it with this :
ArrayList<exempleitem> ExampleList = new ArrayList<>();
ExampleList.add(new exempleitem(R.drawable.ic_android, "Line 1", "Line 2 ", button2.setId(R.id.hydro) ));
ExampleList.add(new exempleitem(R.drawable.ic_baseline_airplanemode_active_24, "Line 3", "Line 4 ",button3.setId(R.id.hel)));
ExampleList.add(new exempleitem(R.drawable.ic_baseline_beach_access_24, "Line 5", "Line 6 ",button4.setId(R.id.lit)));
My problem is that I would like to change the ID of each button, and it doesnt work.
I can't think of anything else right now, and I'm quite a begginner.
I think you don't know how a recyclerview works. It doesn't matter if a button have the same id as another as long as they live in different "cells". Thats the purpose of recyclerviews.
So you have to create a recyclerview adapter and put all the logic in there, the logic will be based on a dataset which is an array probably and your clicks will be based on the position of that array.
You can read more from Google's official guide
Hope it helps!
You shouldn't change the ids and if I am not mistaken, you are not even allowed to do that.
I read in the comments that you want to change the event of a button. Try encapsulating the actions of each button click into methods and then setOnClickListener again on the buttons to change their on click action.
Initial Code before changing action
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dosmthA();
}
});
To change action simply:
view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dosmthB();
}
});
You can even create View.OnClickListener() objects and interchange them in the setOnClickListener() method like so:
View.OnClickListener action = new View.OnClickListener() {
#Override
public void onClick(View view) {
smth();
}
}
view.findViewById(R.id.button_first).setOnClickListener(action);
You can use a ViewHolder and RecyclerView Adapter to set Click listener for each view...
If you share me the adapter code snippet I can give you the code...
😁

What are the parameters for AlertDialog.Builder()?

So I am working on creating my first test app using Android Studio and Kotlin.
Also, should I just not use Kotlin when developing apps? I was told to use Kotlin..
Anyways back to my problem.
I wanted to know what the parameters were for AlertDialog.Builder(this)
I know it's supposed to be this or this#mainactivity but I don't know what the parameter is.
There is no intellisense and I couldnt find any documents.
How about a custom Alert Dialog that yes it is boiler plate code but oh the style!
You need this XML
<?xml version="1.0" encoding="utf-8"?>
<ImageView
android:id="#+id/imgDI"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/caution" />
<TextView
android:id="#+id/tvDAT"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="80dp"
android:layout_marginTop="30dp"
android:text="Delete Note"
android:textColor="#color/color_Black"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvDAC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="80dp"
android:gravity="center"
android:text="Do You Want to DELETE this Note"
android:textColor="#color/color_Black"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnYES"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="240dp"
android:layout_marginTop="110dp"
android:background="#color/color_Transparent"
android:text="DELETE"
android:textColor="#color/color_deepBlue"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnNO"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="110dp"
android:background="#color/color_Transparent"
android:text="CANCEL"
android:textColor="#color/color_deepBlue"
android:textSize="18sp"
android:textStyle="bold" />
here is the button that calls the view
btnDelete.setOnClickListener{
if(etPerson.text.toString().equals("")){
message("No Match Found")
return#setOnClickListener
}
doCustom()
}
And now doCustom IT is a little funky to call the other function
fun doCustom() {
/* This method uses the custom_dialog.xml file created for greater control over
the styling of the Custom Alert Dialog for various screen sizes and to be
able to set the text size of the dialog message text
*/
val makeDialog = LayoutInflater.from(this).inflate(R.layout.custom_dialog,null)
val mBuilder = AlertDialog.Builder(this).setView(makeDialog)
val mAlertDialog = mBuilder.show()
val btnYES = makeDialog.findViewById<Button>(R.id.btnYES)
val btnNO = makeDialog.findViewById<Button>(R.id.btnNO)
mAlertDialog.setCancelable(false)
btnYES.setOnClickListener {
removePerson()
mAlertDialog.dismiss()
}
btnNO.setOnClickListener {
message("Record NOT Deleted")
etPerson.setText("")
Timer().schedule(800){
thisACTIVITY()
}
mAlertDialog.dismiss()
}
mAlertDialog.show()
}
private fun removePerson() {
val dbHandler = DBHelper(this)
val result = dbHandler.deletePerson(etPerson.text.toString())
if (result) {
etPerson.setText("")
message("Record Removed")
Timer().schedule(1000){
thisACTIVITY()
}
}else{
etPerson.setText("NO MATCH -> click View Person List")
btnViewList.visibility = View.VISIBLE
btnEdit.visibility = View.INVISIBLE
btnDelete.visibility =View.INVISIBLE
btnAdd.visibility = View.INVISIBLE
message("NO Match Found")
}
}

Checking at least one radio button is selected from each radiogroup in android?

How do I ensure that user is checked at least one radiobutton from each radiogroup. Like I have this radiogroup:
<RadioGroup
android:id="#+id/myradio_group_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first"
android:checked="true" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="second" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="third" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fourt" />
</RadioGroup>
<RadioGroup
android:id="#+id/myradio_group_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="first"
android:checked="true" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="second" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="third" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="fourt" />
</RadioGroup>
I want to check programmatically if user select at least one radiobutton or not?
Get a reference of the RadioGroup and then call getCheckedRadioButtonId() on the radio group if nothing is selected then the call will return -1.
See public int getCheckedRadioButtonId ()
RadioGroup g = (RadioGroup) findViewById(R.id.rBtnDigits);
// Returns an integer which represents the selected radio button's ID
int selected = g.getCheckedRadioButtonId();
// Gets a reference to our "selected" radio button
RadioButton b = (RadioButton) findViewById(selected);
// Now you can get the text or whatever you want from the "selected" radio button
b.getText();
if (radioGroup.getCheckedRadioButtonId() != -1)
{
// hurray at-least on radio button is checked.
}
else
{
// pls select at-least one radio button.. since id is -1 means no button is check
}
This is the code i have used in one of my quiz app.. Have a look at the code if this helps..
private boolean checkAnswer(){
String answer = getSelection();
if(answer==null) {
Log.d("Questions", "No checkbox selected");
return false;
}
else {
// Do your stuff here
return true;
}
}
private String getSelection(){
if (c1.isChecked())
{
return c1.getText().toString();
}
if (c2.isChecked())
{
return c2.getText().toString();
}
if (c3.isChecked())
{
return c3.getText().toString();
}
if (c4.isChecked())
{
return c4.getText().toString();
}
return null;
}
You can use this method
radioGroup.getCheckedRadioButtonId();
It returns the identifier of the selected radio button in this group. Upon empty selection, the returned value is -1.
As mentioned in the documentation https://developer.android.com/reference/android/widget/RadioGroup.html#getCheckedRadioButtonId()

Categories

Resources