How to Show Custom Dialog on OnBackPressed - java

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()
}
}
}

Related

Android : Add a listener to an icon in a text field

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();
}
});
}
}

TextView doesn't setText inside include layout

I have a custom dialog in which I include another layout. In this layout there are 3 buttons and a TextView none of these is null. If I click the buttons they work correctly. But the TextView doesn't show any text. The text should appears when I click another button. That's how it should works
Custom dialog layout:
<LinearLayout
............
.....
<androidx.cardview.widget.CardView
android:id="#+id/result_card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="2dp"
card_view:cardMaxElevation="2dp"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp"
android:visibility="gone"
app:cardCornerRadius="8dp">
<include android:id="#+id/result_layout" layout="#layout/result_block" />
</androidx.cardview.widget.CardView>
....
....
</LinearLayout>
The result_block layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:background="#color/colorPrimary"
android:orientation="vertical">
<TextView
android:id="#+id/result_txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:text=""
android:textColor="#color/colorWhite"
android:fontFamily="sans-serif-medium"
android:padding="8dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="end"
android:orientation="horizontal">
<ImageButton
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_copy_24px_outlined"
android:layout_marginEnd="16dp"
android:tint="#color/colorWhite"
android:background="?attr/selectableItemBackgroundBorderless"
/>
<ImageButton
android:id="#+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:tint="#color/colorWhite"
android:src="#drawable/ic_share_24px_outlined"
android:background="?attr/selectableItemBackgroundBorderless"
/>
<ImageButton
android:id="#+id/btn3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tint="#color/colorWhite"
android:src="#drawable/ic_volume_up_24px_outlined"
android:background="?attr/selectableItemBackgroundBorderless"
/>
</LinearLayout>
</LinearLayout>
And now the dialog
private void showDiag() {
final View dialogView = View.inflate(getActivity(), R.layout.custom_dialog_layout,null);
final View resultLayout = View.inflate(getActivity(), R.layout.result_block,null);
final Dialog dialog = new Dialog(getActivity(), R.style.MyAlertDialogStyle);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(dialogView);
final TextView resultTxt = resultLayout.findViewById(R.id.result_txt);
final ImageButton btn1 = resultLayout.findViewById(R.id.btn1);
final CardView resultCardView = dialog.findViewById(R.id.result_card_view);
final TextInputEditText editText = dialog.findViewById(R.id.text_edit);
final ImageButton clearText = dialog.findViewById(R.id.clear_text);
MaterialButton resultConfirm = dialog.findViewById(R.id.result_confirm);
ImageButton btn2 = dialogView.findViewById(R.id.copy_btn);
ImageButton btn3 = dialogView.findViewById(R.id.share_btn);
resultConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!editText.getText().toString().equals("")) {
String theWord = editText.getText().toString();
String result = Utils.getSecondWord(theWord);
// result it shows me the correct string with no errors or something else
resultTxt.setText(result); // doesn't work. Not set the text
insertWord(theWord, result);
resultCardView.setVisibility(View.VISIBLE);
resultCardView.setVisibility(View.VISIBLE);
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
// Share btn
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i(TAG, "result: " + resultTxt.getText().toString());
}
});
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
Utils.revealShow(dialogView, true, null, resultConfirm);
}
});
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_BACK){
Utils.revealShow(dialogView, false, dialog, resultConfirm);
return true;
}
return false;
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.show();
}
Everything inside the dialog works correctly but the TextView not. Even if I try to write something else like resultTxt.setText("Hello there"); the text not appears. Any suggestions?
Please you remove the android:text=""in TextView because textview is get default text is empty or you write anything in TextView like android:text="abc"

Exception When handling Custom AlertDialog with ButterKnife

Hello guys iam realy Confused i spent over 17 hours try to fix this Problem but
No hope
Am try to show Custom Dialog with > AlertDialog.Builder when i Click Button but when i run the App and click the button it gives me this Exception
i tried ButterKnife #OnClick Anotation and Casting the Item Inside the Dialog Function like Button item = findviewById(R.id.ItemID);
i search for questions has same problem like mine but useless till i found
this question Multiple injections but i found that its really very old May 29, 2014
The Exception
05-23 21:15:56.630 8769-8769/com.w4ma.soft.tamenly E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.w4ma.soft.tamenly, PID: 8769
java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost.ShowCommentDialog(ShowThePost.java:133)
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost.onClick(ShowThePost.java:159)
at com.w4ma.soft.tamenly.View.CreateandShow.ShowThePost_ViewBinding$1.doClick(ShowThePost_ViewBinding.java:52)
at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
at android.view.View.performClick(View.java:5647)
at android.view.View$PerformClick.run(View.java:22462)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6221)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
Here is my code
ShowThePost.java
#Nullable #BindView(R.id.priceSuggested) EditText txtSuggestprice;
#Nullable #BindView(R.id.txtnotes) EditText txtNotes;
#Nullable #BindView(R.id.btnClose) Button btnclose;
#Nullable #BindView(R.id.btnCommentDone) Button btndone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_the_post);
ButterKnife.bind(this);
}
public void ShowCommentDialog() {
final AlertDialog.Builder alert = new AlertDialog.Builder(context);
view = getLayoutInflater().inflate(R.layout.create_comment,null);
alert.setCancelable(false);
alert.setView(view);
final AlertDialog dialog = alert.create();
// final Dialog dialog = new Dialog(context);
// dialog.setContentView(R.layout.create_comment);
// dialog.setCancelable(false);
// dialog.setTitle("This is Dialog");
// EditText txtSuggestprice = findViewById(R.id.priceSuggested);
// EditText txtNotes = findViewById(R.id.txtnotes);
// Button btnDonee = (Button)findViewById( R.id.btnCommentDone);
// Button btnClosee =(Button)findViewById(R.id.btnClose);
//
// btndone.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
//
// }
// });
// btnclose.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// dialog.dismiss();
//
// }
// });
final String Notes = txtNotes.getText().toString();
final String Description = txtSuggestprice.getText().toString();
alert.setPositiveButton("Done", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toasty.success(context,"Done" + Notes + Description, Toast.LENGTH_LONG).show();
}
}).setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
btndone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Done", Toast.LENGTH_SHORT).show();
}
});
btnclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Closed", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.show();
}
#OnClick(R.id.fabComment)
public void ShowDialog(){
ShowCommentDialog();
}
CreatComment.xml this is the Custom Dialog which should Inflate to the Dialog
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="#dimen/_12sdp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Comment"
android:textSize="#dimen/_22sdp"
android:textColor="#000"
android:textAlignment="center"
android:layout_margin="#dimen/_9sdp"
android:typeface="serif"/>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/_1sdp"
android:background="#color/lightgray"
android:padding="#dimen/_4sdp"/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_4sdp">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/priceSuggested"
android:layout_margin="#dimen/_5sdp"
android:hint="Suggest Price"
android:inputType="number"
android:typeface="serif"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/_4sdp">
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/_5sdp"
android:hint="Notes"
android:id="#+id/txtnotes"
android:typeface="serif"/>
</android.support.design.widget.TextInputLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Done"
android:background="#drawable/btncommentstyle"
android:id="#+id/btnCommentDone"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Close"
android:layout_marginTop="#dimen/_4sdp"
android:background="#drawable/btncommentstyle"
android:id="#+id/btnClose"/>
</LinearLayout>
</android.support.v7.widget.CardView>
The exception is caused by this line:
final String Notes = txtNotes.getText().toString();
As described in the reason, the txtNotes member is null, which means that the binding did not work (probably the view with txtnotes id was not found).
From what I see, you call ButternKnife.bind() for the activity which has the activity_show_the_post layout as content view. But the view with txtnotes id is actually in the create_comment layout, of which ButterKnife knows nothing about, and doesn't even exist at that time. Thus, the binding fails, no reference to txtnotes is created and you later get a NPE.
You need to bind the views for create_comment.xml too
view = getLayoutInflater().inflate(R.layout.create_comment,null);
Butterknife.bind(view,this);
alert.setCancelable(false);
alert.setView(view);
final AlertDialog dialog = alert.create();

Not able to get id of radiobutton via getCheckedRadioButtonId()

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.

Pass data from dialog to activity Android

I have problem.
I made method which creates Dialog with my own layout. And I have no idea how to pass values (Strings) from my EdiText and asing to any variable in my Activity.
In comments you can see how I was trying to solve this.
Java method
public void makeDialog(){
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog_ip);
dialog.setTitle("IP connection");
// Todo passing value from dialog to activity
// final EditText ipValueConnection = (EditText)findViewById(R.id.ipValueConnection);
// ipValueConnection.setOnClickListener(this);
// EditText portValueConnection = (EditText)findViewById(R.id.portValueConnection);
// Toast.makeText(context, ipValueConnection.getText().toString(), Toast.LENGTH_LONG).show();
Button dialogButtonLogin = (Button) dialog.findViewById(R.id.dialogButtonLogin);
// if button is clicked, close the custom dialog
dialogButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tryToConnect();
dialog.dismiss();
}
});
// set the custom dialog components - text, image and button
// TextView text = (TextView) dialog.findViewById(R.id.IP);
dialog.show();
}
XML layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:src="#drawable/antena"
android:layout_width="220dp"
android:layout_height="120dp"
android:scaleType="centerInside"
android:background="#FFFFBB33"
android:contentDescription="#string/app_name"
android:adjustViewBounds="true"
/>
<EditText
android:id="#+id/ipValueConnection"
android:inputType="textEmailAddress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="IP" />
<EditText
android:id="#+id/portValueConnection"
android:inputType="textPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="16dp"
android:fontFamily="sans-serif"
android:hint="PORT"/>
<Button
android:id="#+id/dialogButtonLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:layout_marginTop="5dp"
/>
</LinearLayout>
Create a interface
public interface OnClickInterface {
public void onClick();
}
call it instantiate it in your activity onCreate()
OnClickInterface onClickInterface = new OnClickInterface() {
#Override
public void onClick() {
//Call Method from here
requiredMethod();
}
};
//And in your dialog classs or method
public void makeDialog(OnClickInterface onClickInterface){
//Your code
dialogButtonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClickInterface.onClick();
dialog.dismiss();
}
});
}
The error you are getting means that a reference to the editText cannot be found in the current layout file. You have find the EditText in the custom dialog view instead of the activity view.
So instead of:
final EditText ipValueConnection =(EditText)findViewById(R.id.ipValueConnection);
use:
final EditText ipValueConnection =(EditText)dialog.findViewById(R.id.ipValueConnection);
If i have understood your question correctly,
your edit text is in dialog_ip so you need to use
final EditText ipValueConnection = (EditText) dialog.findViewById(R.id.ipValueConnection);
Then you can get text from edit text as
String text= ipValueConnection.getText().toString;
And use that variable in your activity.

Categories

Resources