I am trying to make a custom dialog box which gives radio buttons to select from n then diplay text of radio button in the textfield. This is what i tried..
My Layout for dialog box is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioGroup
android:id="#+id/rg_carType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="vertical">
<RadioButton
android:id="#+id/rb_hatchD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hatchback(Diesel)" />
<RadioButton
android:id="#+id/rb_hatchP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hatchback(Petrol)" />
<RadioButton
android:id="#+id/rb_sedanD"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sedan(Diesel)" />
<RadioButton
android:id="#+id/rb_sedanP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sedan(Petrol)" />
<RadioButton
android:id="#+id/rb_suv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SUV" />
</RadioGroup>
<ImageView
android:id="#+id/iv_carType"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:layout_toRightOf="#+id/rg_carType"
/>
<Button
android:id="#+id/btn_confirmCar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/rg_carType"
android:layout_centerHorizontal="true"
android:background="#drawable/button_2"
android:text="Confirm"
android:textColor="#fff" />
And the function for custom dialog box is
private void diplayCartype() {
final Dialog dialog_car = new Dialog(FinalActivity.this);
final RadioButton rb_select;
RadioGroup rg_carType;
ImageView iv_carType;
Button btn_confirmCar;
String sCar="?";
dialog_car.setTitle("Select Car Type");
dialog_car.setContentView(R.layout.dialog_cartype);
iv_carType=(ImageView)dialog_car.findViewById(R.id.iv_carType);
btn_confirmCar=(Button)dialog_car.findViewById(R.id.btn_confirmCar);
rg_carType=(RadioGroup)dialog_car.findViewById(R.id.rg_carType);
int selected=rg_carType.getCheckedRadioButtonId();
rb_select=(RadioButton)dialog_car.findViewById(selected);
switch(selected)
{
case R.id.rb_hatchD:
iv_carType.setImageResource(R.drawable.hatch_d);
sCar=rb_select.getText().toString();
break;
case R.id.rb_hatchP:
iv_carType.setImageResource(R.drawable.hatch_p);
sCar=rb_select.getText().toString();
break;
case R.id.rb_sedanD:
iv_carType.setImageResource(R.drawable.sedan_d);
sCar=rb_select.getText().toString();
break;
case R.id.rb_sedanP:
iv_carType.setImageResource(R.drawable.sedan_p);
sCar=rb_select.getText().toString();
break;
case R.id.rb_suv:
iv_carType.setImageResource(R.drawable.suv);
sCar=rb_select.getText().toString();
break;
default:
iv_carType.setImageResource(R.drawable.suv);
sCar="default";
}
final String finalSCar = sCar;
btn_confirmCar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv_carType.setText(finalSCar);
dialog_car.dismiss();
}
});
dialog_car.show();
}
The problem is that the switch case executes only default condition, that means its not getting id to check. Thanks in advance.. :)
this code work for me
public class RadioButtonFragment extends DialogFragment {
String singleitem;
private int witch;
private MySharedPreferences mySharedPreferences = new MySharedPreferences();
private String[] item = {"Naskh asiatype", "Fajer noori Nastaleeq", "Pak nastaleeq (default)"};
#Override
public void onResume() {
super.onResume();
witch= mySharedPreferences.loadIntPrefs(Constants.RADIO_BUTTON_INDEX_KEY,2,getActivity());
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
witch= mySharedPreferences.loadIntPrefs(Constants.RADIO_BUTTON_INDEX_KEY,2,getActivity());
builder.setTitle("please selet any fount").setSingleChoiceItems(item, witch, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
singleitem= item[which];
mySharedPreferences.saveStringPrefs(Constants.FONT_KEY,singleitem,getActivity());
mySharedPreferences.saveintPrefs(Constants.RADIO_BUTTON_INDEX_KEY,which,getActivity());
Toast.makeText(getContext(),"Font is selected"+which,Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
and call to build this fragment
RadioButtonFragment radioButtonFragment = new RadioButtonFragment();
radioButtonFragment.show(getSupportFragmentManager(), RadioButtonFragment_TAG);
You need read the value at the right time (button click). Do this:
btn_confirmCar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rg_carType=(RadioGroup)dialog_car.findViewById(R.id.rg_carType);
int selected=rg_carType.getCheckedRadioButtonId();
rb_select=(RadioButton)dialog_car.findViewById(selected);
switch(selected)
{
case R.id.rb_hatchD:
iv_carType.setImageResource(R.drawable.hatch_d);
break;
case R.id.rb_hatchP:
iv_carType.setImageResource(R.drawable.hatch_p);
break;
case R.id.rb_sedanD:
iv_carType.setImageResource(R.drawable.sedan_d);
break;
case R.id.rb_sedanP:
iv_carType.setImageResource(R.drawable.sedan_p);
break;
case R.id.rb_suv:
iv_carType.setImageResource(R.drawable.suv);
break;
default:
iv_carType.setImageResource(R.drawable.suv);
sCar="default";
}
if (!sCar.equals("default"))
sCar = rb_select.getText().toString();
tv_carType.setText(sCar);
dialog_car.dismiss();
}
});
dialog_car.show();
}
About getCheckedRadioButtonId()
Returns the identifier of the selected radio button in this group.
Upon empty selection, the returned value is -1.
There is no selected RadioButton at the moment when you are trying to check for selected one.
dialog_car.setContentView(R.layout.dialog_cartype);
// at this point you have newly created view hierarchy and
// RadioGroup has no selected items
iv_carType=(ImageView)dialog_car.findViewById(R.id.iv_carType);
btn_confirmCar=(Button)dialog_car.findViewById(R.id.btn_confirmCar);
rg_carType=(RadioGroup)dialog_car.findViewById(R.id.rg_carType);
// still has no selected items, next call returns -1 as well
int selected=rg_carType.getCheckedRadioButtonId();
You should use getCheckedRadioButtonId() from handler of some extra button (e.g. "OK") to be sure that user has seen your radio buttons and has enough time to select something.
You must use an interface (Listener) for listening to User Inputs. For example you can use RadioGroup.setOnCheckedChangeListener and then place your switch statement in it.
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.radioButtonId:
// Your Code Here
break;
---
}
}
});
Your current code would statically pick the default values of initially assigned states. Above enhancements would help you handle user inputs dynamically.
Related
The problem that I have faced:
The Female radiobutton checked can show the result in another activity successfully, but the Male radiobutton checked cannot show the result in another activity.
MainActivity17.java
public class MainActivity17 extends AppCompatActivity {
RadioButton male, female;
Double maleAmount;
Double femaleAmount;
String textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main17);
}
public void onRadioButtonClicked(final View view) {
final boolean checked = ((RadioButton) view).isChecked();
final EditText editTextUser = findViewById(R.id.editTextUser);
final TextView textViewOutput = findViewById(R.id.textViewOutput);
male = findViewById(R.id.ButtonMale);
female = findViewById(R.id.ButtonFemale);
Button btn = findViewById(R.id.btnNext);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NumberFormat nm = NumberFormat.getNumberInstance();
final Double userInput = Double.parseDouble(editTextUser.getText().toString());
switch (view.getId()) {
case R.id.ButtonMale:
if (checked)
maleAmount = (userInput * 40);
textViewOutput.setText(nm.format(maleAmount));
break;
case R.id.ButtonFemale:
if (checked)
femaleAmount = (userInput * 40 * 2);
textViewOutput.setText(nm.format(femaleAmount));
break;
}
Intent i = new Intent(MainActivity17.this, MainActivity18.class);
textview = textViewOutput.getText().toString();
i.putExtra("String", textview);
startActivity(i);
finish();
}
});
}
}
main_activity17.xml
<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=".MainActivity17">
<EditText
android:id="#+id/editTextUser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="6"
android:hint="Enter Amount"
android:inputType="numberDecimal" />
<RadioGroup
android:id="#+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="60sp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/editTextUser"
android:layout_marginTop="20dp">
<RadioButton
android:id="#+id/ButtonMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="true"
android:onClick="onRadioButtonClicked"
android:text="Male" />
<RadioButton
android:id="#+id/ButtonFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/radioGroup"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_weight="1"
android:onClick="onRadioButtonClicked"
android:text="Female" />
</RadioGroup>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="16dp"
android:layout_marginLeft="43dp"
android:layout_marginStart="43dp"
android:text="Next" />
<TextView
android:id="#+id/textViewOutput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/btnNext"
android:textSize="30sp" />
</RelativeLayout>
MainActivity18.java - I want to show the result in this activity
public class MainActivity18 extends AppCompatActivity {
TextView textView;
String valFromAct1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main18);
textView = findViewById(R.id.textView18);
valFromAct1 = getIntent().getExtras().getString("String");
textView.setText(valFromAct1);
}
}
main_activity18.xml
<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=".MainActivity18">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView18"
android:text="this is activity 2"
android:layout_centerHorizontal="true"
android:textSize="30dp"/>
</RelativeLayout>
First of all, I think you need some modification in the first activity.
you should not bind your views in the onclick method and it is not a good idea to add set the onClick method in the onRadioButton Click. instead, use disable attribute of the button.
MainActivity17.java
public class MainActivity17 extends AppCompatActivity {
RadioButton male, female;
Double maleAmount;
Double femaleAmount;
String textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main17);
final EditText editTextUser = findViewById(R.id.editTextUser);
final TextView textViewOutput = findViewById(R.id.textViewOutput);
male = findViewById(R.id.ButtonMale);
female = findViewById(R.id.ButtonFemale);
Button btn = findViewById(R.id.btnNext);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
NumberFormat nm = NumberFormat.getNumberInstance();
final Double userInput = Double.parseDouble(editTextUser.getText().toString());
switch (view.getId()) {
case R.id.ButtonMale:
if (checked)
maleAmount = (userInput * 40);
textViewOutput.setText(nm.format(maleAmount));
break;
case R.id.ButtonFemale:
if (checked)
femaleAmount = (userInput * 40 * 2);
textViewOutput.setText(nm.format(femaleAmount));
break;
}
Intent i = new Intent(MainActivity17.this, MainActivity18.class);
textview = textViewOutput.getText().toString();
i.putExtra("String", textview);
startActivity(i);
finish();
}
});
}
public void onRadioButtonClicked(final View view) {
final boolean checked = ((RadioButton) view).isChecked();
}
}
But if you want to use multiple radio buttons you can use the below method for notifying the selected item:
// Add the Listener to the RadioGroup
radioGroup.setOnCheckedChangeListener(
new RadioGroup
.OnCheckedChangeListener() {
#Override
// The flow will come here when
// any of the radio buttons in the radioGroup
// has been clicked
// Check which radio button has been clicked
public void onCheckedChanged(RadioGroup group,
int checkedId)
{
// Get the selected Radio Button
switch (checkedId) {
case R.id.ButtonMale:
maleAmount = (userInput * 40);
textViewOutput.setText(nm.format(maleAmount));
break;
case R.id.ButtonFemale:
femaleAmount = (userInput * 40 * 2);
textViewOutput.setText(nm.format(femaleAmount));
break;
}
}
});
i am a beginner in application development and i like to ask a question that i tried my best to get an answer in google but i failed.
So,
in my application (in java) i am using too text fields :
<com.google.android.material.textfield.TextInputLayout
android:layout_marginBottom="20dp"
android:id="#+id/start_date_Layout"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginHorizontal="20dp"
app:helperText="Start Date"
app:endIconMode="custom"
app:endIconDrawable="#drawable/ic_date"
>
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/start_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="dd/mm/yy"
/>
</com.google.android.material.textfield.TextInputLayout>
I added a listener to my end icon like that :
this.startDateLayout = v.findViewById(R.id.start_date_Layout);
this.startDateLayout.setEndIconOnClickListener(this);
My problem is when i try to get the view that the user clicked :
#Override
public void onClick(View v) {
if (v.getParent() == this.startDateLayout){
Toast.makeText(this.context, "click", Toast.LENGTH_LONG).show();
}
}
the toast never appear and the if condition is never true, my question is how can i get the view on witch the user clicked. thanks for reading i hope i was clear as much as possible.
For me only doing following works:
final TextInputLayout textInputLayout = findViewById(R.id.start_date_Layout);
textInputLayout.setEndIconOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// DO STUFF
}
});
As you're explicitly setting listener on End icon only you shouldn't be worried about verifying viewId.
Just use:
startDateLayout = v.findViewById(R.id.start_date_Layout);
startDateLayout.setEndIconOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// DO something....
}
});
Simple kotlin:
b.dateLabel.setEndIconOnClickListener {
Toast.makeText(requireContext(), "date", Toast.LENGTH_SHORT).show()
}
First what I can notice in the above code, you're trying to listen to click events on your View
A simple way to do so is change your onClick() method to below
public void onClick(View v) {
if (v.getId() == R.id.start_date_Layout){
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG).show();
}
}
I believe I could help
If you are using EditText, then try setting an onFocusChangeListner to the editText instead of onClickListner.
startDateLayout.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus) {
// Show your code when has focus
} else {
// when it does not have focus
}
}});
The question is simple, You can you a FragmeLayout or LinearLayout, EditText and an ImageView for achieving the solution, it will be similar to the TextInputEditText but you will have much more control over View Hierarchy, let me show you how you can achieve it, for the sake of simplicity as you are a beginner I'll use linear Layout
Create A FrameLayout or LinearLayout and then create an EditText and an ImageView like
XML:
<LinearLayout
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#DCDFDF"
android:orientation="horizontal"
tools:ignore="MissingConstraints">
<ImageView
android:layout_gravity="center_vertical"
android:id="#+id/imageViewTitle"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_margin="15dp"
android:src="#drawable/android"
tools:ignore="ContentDescription" />
<EditText
android:layout_gravity="center_vertical"
android:id="#+id/editTextTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:background="#DCDFDF"
android:gravity="top"
android:hint="Start Date"
android:paddingTop="10dp"
android:textAlignment="gravity"
android:importantForAutofill="no" />
</LinearLayout>
Java
public class MainActivity extends AppCompatActivity {
EditText editTextTitle;
ImageView imageViewTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextTitle = findViewById(R.id.editTextTitle);
imageViewTitle = findViewById(R.id.imageViewTitle);
imageViewTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Do your work here
Toast.makeText(MainActivity.this, "ImageView Pressed", Toast.LENGTH_SHORT).show();
}
});
}
}
I want to show a custom dialog box whenever someone clicks on the back button on the main Activity to exit the app.
I tried multiple methods but non worked for me. I simply want to have 4 icons (buttons) and a text line in that dialog box along with "exit" the app option.
Is there any workable solution you guys can suggest??
To make an action when user clicks the back button you can simplly override the onBackPressed() , to show a custom dialog you need to do 2 things, first create the layout of the dialog with the 4 buttons and the text you want.
custom_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:background="#3E80B4"
android:orientation="vertical" >
<TextView
android:id="#+id/txt_dia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp"
android:text="Your text goes here"
android:textColor="#android:color/white"
android:textSize="15dp"
android:textStyle="bold"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#3E80B4"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_yes"
android:layout_width="100dp"
android:layout_height="30dp"
android:background="#android:color/white"
android:clickable="true"
android:text="Yes"
android:textColor="#5DBCD2"
android:textStyle="bold" />
<Button
android:id="#+id/btn_no"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:background="#android:color/white"
android:clickable="true"
android:text="No"
android:textColor="#5DBCD2"
android:textStyle="bold" />
<Button
android:id="#+id/btn_exit"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:background="#android:color/white"
android:clickable="true"
android:text="Exit"
android:textColor="#5DBCD2"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
Then Create a custom dialog class exteding Dialog and implements OnClickListener
public class CustomDialogClass extends Dialog implements
android.view.View.OnClickListener {
public CustomDialogListener listener;
public Dialog d;
public Button yes, no, exit;
public CustomDialogClass(#NonNull Context context,
CustomDialogListener listener) {
super(context);
this.listener = listener ;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
yes = (Button) findViewById(R.id.btn_yes);
no = (Button) findViewById(R.id.btn_no);
exit = (Button) findViewById(R.id.btn_exit);
yes.setOnClickListener(this);
no.setOnClickListener(this);
exit.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_yes:
listener.onYesButtonClicked();
break;
case R.id.btn_no:
listener.onNoButtonClicked();
break;
case R.id.btn_exit:
listener.onExitButtonClicked();
break;
default:
break;
}
dismiss();
}
public interface CustomDialogListener {
public void onYesButtonClicked() ;
public void onNoButtonClicked() ;
public void onExitButtonClicked() ;
}
}
Finally at the MainActivity class ovverride the onBackPressed() , show the dialog and handle all button clicks
#Override
public void onBackPressed() {
CustomDialogClass cd = new CustomDialogClass(this, new CustomDialogClass.CustomDialogListener() {
#Override
public void onYesButtonClicked() {
Toast.makeText(MainActivity.this, "Yes Clicked", Toast.LENGTH_LONG).show();
}
#Override
public void onNoButtonClicked() {
Toast.makeText(MainActivity.this, "No Clicked", Toast.LENGTH_LONG).show();
}
#Override
public void onExitButtonClicked() {
Toast.makeText(MainActivity.this, "Exit Clicked", Toast.LENGTH_LONG).show();
}
});
cd.show();
}
Try to override your main activitys onBackPressed() function. If users press the back button, it will be triggered. Then you can pop-up your custom dialog and if the exit button is clicked on your dialog you can call super.onBackPressed() or finish(). This will close on your application.
UPDATE
class MainActivity : AppCompatActivity() {
private var dialog: Dialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onBackPressed() {
if (dialog == null || dialog?.isShowing == false) {
dialog = AlertDialog.Builder(this)
.setTitle("Some title")
.setMessage("Some message")
.setPositiveButton("Exit") { dialog, which ->
super.onBackPressed()
}
.setNeutralButton("Action 1") { dialog, which ->
//DO SOME ACTION
dialog.cancel()
}
.setNegativeButton("Action 2") { dialog, which ->
//DO SOME ACTION
dialog.cancel()
}
.create()
dialog!!.show()
}
}
}
I want to make an alert dialog that contains a single-choice list item which will help the user choose the theme of the app. I have read on developer's website(Developers Website) how to make the multiple-choice items but I don't quite get how to make the single-choice list item
Thanks in Advance.
//MY CODE
public class ThemeDialog extends DialogFragment {
ArrayList mSelectedItems = new ArrayList(); // Track the selected items
public static ThemeDialog newInstance(){
ThemeDialog f = new ThemeDialog();
return f;
}
//Single-choice Item code
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
dialog.setTitle("Please Select");
dialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Action when cancel is clicked
dialog.dismiss();
}
});
CharSequence[] cs = new CharSequence[]{"Item-1", "Item-2","Item-3"};
dialog.setSingleChoiceItems(cs, defaultSelectedPosition, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Action when any item is clicked
dialog.dismiss();
}
});
return dialog.create();
}
dialog.setSingleChoiceItems(cs, position, selectItemListener); will create the single choice dialog.
create xml layout file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:background="#color/colorWhite"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/colorPrimary">
</View>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorWhite"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="please select a theme"
android:textColor="#color/colorRed"
android:textSize="18sp" />
<RadioGroup
android:id="#+id/cancle_booking_radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<RadioButton
android:id="#+id/theme1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme1" />
<RadioButton
android:id="#+id/theme2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme2" />
<RadioButton
android:id="#+id/theme3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme3" />
<RadioButton
android:id="#+id/theme4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme4" />
<RadioButton
android:id="#+id/theme5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:buttonTint="#color/colorPrimary"
android:text="theme5" />
</RadioGroup>
</LinearLayout>
now create custom dialog
final Button btnCancelbooking;
final TextView tvHideCancelDialog;
final RadioButton theme1, theme2, theme3, theme4, theme6;
final Dialog cancelDialog = new Dialog(BookingConfirmClass.this, R.style.DialogSlideAnim);
//cancelDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); /*use when not set in style file*/
cancelDialog.setContentView(R.layout.custom_cancel_booking);
getWindow().setGravity(Gravity.BOTTOM);
cancelDialog.show();
theme1 = (RadioButton) cancelDialog.findViewById(R.id.theme1);
theme2 = (RadioButton) cancelDialog.findViewById(R.id.theme2);
theme3 = (RadioButton) cancelDialog.findViewById(R.id.theme3);
theme4 = (RadioButton) cancelDialog.findViewById(R.id.theme4);
theme6 = (RadioButton) cancelDialog.findViewById(R.id.theme5);
final RadioGroup radioGroup = (RadioGroup) cancelDialog.findViewById(R.id.cancle_booking_radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
View radioButton = radioGroup.findViewById(checkedId);
int index = radioGroup.indexOfChild(radioButton);
switch (index) {
case 0:
//do your action for theme 1
break;
case 1:
//do your action for theme 2
break;
case 2:
//do your action for theme 3
break;
case 3:
//do your action for theme 4
break;
case 4:
//do your action for theme 5
break;
}
}
});
Using a final variable obviously won't work (since it can only be assigned once, at declaration time). So-called "global" variables are usually a code smell (especially when they become part of an Activity class, which is usually where AlertDialogs are created). The cleaner solution is to cast the DialogInterface object to an AlertDialog and then call getListView().getCheckedItemPosition(). Like this:
new AlertDialog.Builder(this)
.setSingleChoiceItems(items, 0, null)
.setPositiveButton(R.string.ok_button_label, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
// Do something useful withe the position of the selected radio button
}
})
.show();
To make it more customize look at this -How to design Single Selection Dialog?
You need to add Radio buttons inside the RadioGroup Tag in ur dialog xml file.
custom_dialog.xml
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/RGroup">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blue Theme"
android:id="#+id/bluetheme"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Black Theme"
android:id="#+id/blacktheme"/>
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Brown Theme"
android:id="#+id/browntheme" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Orange Theme"
android:id="#+id/orangetheme"/>
</RadioGroup>
Just attach this xml with dialog fragment...this is just simple example..u can use it in ur way also
public class DFragment extends DialogFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.custom_dialog, container,
false);
getDialog().setTitle("DialogFragment Tutorial");
// Do something else
return rootView;
}
}
I am trying to make a checkbox in android studio/java that if checked will result in a subset of other checkboxes checkable and checked.
The developer site says:
abstract void setChecked(boolean checked)
Change the checked state of the view
But this hasn't worked for me.
Current code:
Java:
package crc.cybereye;
public class CreateNew extends Activity {
LinearLayout background;
Button btnBack;
CheckBox checkbox_structural_info;
CheckBox checkbox_years_of;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
background = (LinearLayout) findViewById(R.id.background);
setContentView(R.layout.activity_create_new);
btnBack = (Button) findViewById(R.id.btnBack);
checkbox_years_of = (CheckBox) findViewById(R.id.checkbox_years_of);
checkbox_floors_above = (CheckBox) findViewById(R.id.checkbox_floors_above);
checkbox_structural_info = (CheckBox) findViewById(R.id.checkbox_structural_info);
// setUpIntroCheckBoxes(); // Add change listeners to check boxes
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), NewFormActivity.class);
startActivityForResult(intent, 0);
}
});
}
More Java:
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.checkbox_structural_info:
if (checked){
checkbox_years_of checked.setChecked(true) //ERROR HERE
}
break;
case R.id.checkbox_years_of:
if (checked){
}
break;
XML:
<TableRow android:layout_marginTop="10dp">
<TextView
android:text="#string/structural_info"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
/>
<CheckBox android:id="#+id/checkbox_structural_info"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onCheckboxClicked"/>
</TableRow>
<TableRow>
<TextView
android:text="#string/years_of"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
/>
<CheckBox android:id="#+id/checkbox_years_of"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onCheckboxClicked"/>
<TableRow>
There is an error saying that it cannot resolve method setChecked(boolean).
My code currently is just trying to get the structural_info checkbox to check the years_of checkbox if it is checked, but I also want to make years_or only checkable if structural_info is checked, I haven't got there yet because I was still stuck on this issue.
Thanks so much for any help in advance.
As requested by the creator of the post, i'm adding the comment as an answer:
You're calling setChecked to checked wich is a boolean variable.
You shoud write:
checkbox_years_of.setChecked(true)
Instead of
checkbox_years_of checked.setChecked(true)