How to make single-choice item - java

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

Related

How do I make a Dialog Fragment's background invisible?

I used youtuber Coding in Flow's method to create a custom dialog. I've been trying all day to make the dialog's background transparent. I've used every single method I've found online. Non worked.
Here's how it goes:
First here's the Dialog layout layout_dialog.xml :
<RelativeLayout
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="match_parent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:background="#drawable/dialog_background">
<!-- The contents of the Dialog go here -->
</RelativeLayout>
<ImageView
android:id="#+id/iconImageView2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="0dp"
android:background="?attr/actionBarItemBackground"
android:scaleType="fitCenter"
app:srcCompat="#android:mipmap/sym_def_app_icon" />
</RelativeLayout>
Here's the Dialog class:
public class DialogBrightness extends AppCompatDialogFragment {
//declare whatever variables here
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
builder.setView(view)
.setTitle("Login")
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//get whatever values
listener.apply(//values);
}
});
//findViewById for your dialog contents here
return builder.create();
}
public interface DialogBrightnessListener {
void apply(//values);
}
}
And here's the Dialog being called from the Main activity:
DialogBrightness dialogBrightness = new DialogBrightness();
dialogBrightness.show(getSupportFragmentManager(), "Brightness Dialog");
This is how the Dialog appears:
I'm trying to make the top white part invisible. Nothing works!
Try this:
put the code below in the onCreateDialog:
// set the dialog background to transparent
getDialog().getWindow().setBackgroundDrawable(newColorDrawable(Color.TRANSPARENT));
// remove background dim
getDialog().getWindow().setDimAmount(0);
You can design the layout like following. There is an extra layout, but in case of dialogs, it will help
Try this:
set the background color of the parent layout to:
android:background="#android:color/transparent"
like this:
<RelativeLayout
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="match_parent"
android:background="#android:color/transparent" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:background="#drawable/dialog_background">
<!-- The contents of the Dialog go here -->
</RelativeLayout>
<ImageView
android:id="#+id/iconImageView2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="0dp"
android:background="?attr/actionBarItemBackground"
android:scaleType="fitCenter"
app:srcCompat="#android:mipmap/sym_def_app_icon" />
</RelativeLayout>

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.

How can I create a popup menu to be shown when I click on an item in listview(android studio)?

I'm new to android developing...
I've created a listview using Strings and Array Adapter in setting.java:
public class setting extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.setting_layout);
String[] settingOptions = new String[]{getString(R.string.settingInterface), getString(R.string.settingLanguages), getString(R.string.settingInfo)};
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, android.R.id.text1, settingOptions);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
}
and this is my setting_layout.xml:
<?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="match_parent">
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
setting_layout Activity(listView)
I want to create a popup menu for Languages item that when I click on it,shows some other languages translations.
I've created a string.xml in other languages but I don't know how to use it in popup menu.
1:How can I make a popup menu shown when I click on Languages item?
2:How to put other languages in popup menu?
Thanks in advance
for pop up you can create a dialog using dialog builder, it can be a custom one(xml layout), or can be created dynamically (programmatically using java)
check out this code for a pop up view :)
for example I have this function that I call inside the onClick:
private void showFlavorDialog(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
View promptView;
LayoutInflater layoutInflater = LayoutInflater.from(myActivity.this); //this gets the custom layout inflater
promptView = layoutInflater.inflate(R.layout.dialog_flavors_ar, null); // here you put the custom xml leyout name
final EditText editText = (EditText) promptView.findViewById(R.id.editText_note); //my layout has an edit text and button in it and I want to use it, so call the findviewbyid
Button add_note = (Button) promptView.findViewById(R.id.button_note);
editText.setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI); //this removes full screen keyboard, so the keyboard doesnt take the whole screen.
add_note.setOnClickListener(new View.OnClickListener() { //onClick for the button
#Override
public void onClick(View v) {
otherNote_b = true;
flavor = editText.getText().toString();
new httpSetFlavor().execute();
alertDialogFL.cancel();
}
});
if (selectedflavorNameEn.size() > 1) {
flavorsGrid = (GridView) promptView.findViewById(R.id.gridView_flavors); // I also have a gridview in the layout
flavorsGridAdapter adapter = new flavorsGridAdapter(OrderActivityAr.this,
selectedflavorNameEn);
flavorsGrid.setAdapter(adapter); // this is a custom adapter for the grid which you wont need
}
alertDialogBuilder.setTitle(R.string.flavor_ar); //title of the popup window
alertDialogBuilder.setView(promptView); //set view of the popup to your custom view
alertDialogBuilder.setCancelable(true); //this makes the popup cancelable on back button pressed
alertDialogBuilder.setPositiveButton(R.string.delete_flavor_ar, new DialogInterface.OnClickListener() { //this is a button for the popup if you want one
public void onClick(DialogInterface dialog, int id) {
deleteFlavor = true;
new httpSetFlavor().execute();
}
});
alertDialogBuilder.setNegativeButton(R.string.back_ar, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialogFL = alertDialogBuilder.create(); //here you create the dialog using its builder
alertDialogFL.show(); // show it on screen
}
and this is my custom layout xml file, so you can just put any layout you want in it and use it later :)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<GridView
android:layout_width="wrap_content"
android:layout_height="150dp"
android:id="#+id/gridView_flavors"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:numColumns="3"
android:horizontalSpacing="2dp"
android:verticalSpacing="2dp" />
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/gridView_flavors"
android:layout_marginTop="5dp">
<Button
style="?android:attr/buttonStyleSmall"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:layout_width="wrap_content"
android:singleLine="true"
android:layout_height="wrap_content"
android:text="#string/add_note_ar"
android:id="#+id/button_note"
android:layout_below="#+id/gridView_flavors"
android:textSize="20dp"
android:background="#drawable/button_plain_green"
android:textColor="#000"
android:layout_weight="0" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText_note"
android:layout_below="#+id/gridView_flavors"
android:layout_toRightOf="#+id/other_text"
android:layout_marginTop="2dp"
android:layout_toLeftOf="#+id/button_note"
android:layout_toStartOf="#+id/button_note"
android:layout_weight="1"
android:gravity="right" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/other_note_ar"
android:id="#+id/other_text"
android:layout_below="#+id/gridView_flavors"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/editText_note"
android:gravity="center"
android:textSize="20dp"
android:layout_weight="0"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp" />
<com.andexert.library.RippleView
android:layout_width="wrap_content"
android:id="#+id/ripple_button"
android:layout_weight="0"
android:layout_height="wrap_content"></com.andexert.library.RippleView>
</TableRow>
</RelativeLayout>
this is the look of the layout:
and in your case you can use listview in the custom layout as well :) but with custom list item for example a radio button.
as for displaying other languages saved in xml
well you should have them saved in res/strings.xml
you can use the strings in an array of strings like this:
String strArray[]={
getResources().getString(R.string.string1),
getResources().getString(R.string.string2),
getResources().getString(R.string.string3),
getResources().getString(R.string.string4)
};

How to replace default android dialog list with custom dialog list

I have designed a custom layout for mydialog list that will enable user select only one option from the list and I would like to use it instead of the default dialog. I really don't know how to do this.
I have this fragment interface shown below;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;`
public class SingleChoiceClass extends DialogFragment {`
final CharSequence[] items = {"b1", "b2", "b3", "b4"};
String selection;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());`
builder.setTitle("Choose").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
switch (arg1){
case 0:
selection = (String) items[arg1];
break;
case 1:
selection = (String) items[arg1];
break;
case 2:
selection = (String) items[arg1];
break;
case 3:
selection = (String) items[arg1];
break;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Display toast with the user's selection
Toast.makeText(getActivity(), "Your choice is : " + selection, Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
And my custom layout is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="350dp"
android:layout_height="350dp"
android:background="#color/button_material_light"
android:layout_gravity="center">
<TextView
android:layout_width="350dp"
android:layout_height="50dp"
android:text="#string/textview"
android:layout_gravity="top"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:layout_marginTop="20dp"
android:textSize="30sp"
android:textAlignment="center"
android:textStyle="normal"
android:id="#+id/textview" />
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:layout_width="match_parent"
android:layout_height="55dp"
android:text="#string/radio1"
android:checked="false"
android:id="#+id/radio1"
android:textSize="25sp"
android:background="#2bf308"
android:clickable="true" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="55dp"
android:checked="false"
android:text="#string/radio2"
android:id="#+id/radio2"
android:textSize="25sp"
android:background="#f4fd02"
android:clickable="true" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="55dp"
android:text="#string/radio3"
android:checked="false"
android:id="#+id/radio3"
android:textSize="25sp"
android:background="#fb8e35"
android:clickable="true" />
<RadioButton
android:layout_width="match_parent"
android:layout_height="55dp"
android:text="#string/radio4"
android:checked="false"
android:id="#+id/radio4"
android:textSize="25sp"
android:background="#fc3434"
android:clickable="true" />
</RadioGroup>
<Button
android:layout_width="match_parent"
android:layout_height="65dp"
android:text="#string/button"
android:id="#+id/button2"
android:layout_gravity="center_horizontal"
android:textSize="25sp"
android:clickable="true" />
</LinearLayout>
Code works fine but I need to use my custom dialog instead of the default. Thanks in advance.
Please try out this
//Please try this
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog dailog = new AlertDialog(getActivity());`
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.custom_layout, null);
dialog.setTitle("Choose").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
switch (arg1){
case 0:
selection = (String) items[arg1];
break;
case 1:
selection = (String) items[arg1];
break;
case 2:
selection = (String) items[arg1];
break;
case 3:
selection = (String) items[arg1];
break;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Display toast with the user's selection
Toast.makeText(getActivity(), "Your choice is : " + selection, Toast.LENGTH_SHORT).show();
}
});
dialog.setView(view);
return view;
}
I am updating my answer as you want a ListView as custom view. First in your custom layout add a listView like below :
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
Next you will need to create a adapter to set to that created ListView, you can do something like below in your onCreateDialog() method
public Dialog onCreateDialog(Bundle savedInstanceState) {
ListView listView;
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.custom_layout, null);
listView = (ListView)dialogView.findViewById(R.id.listView); // inflating from custom layout.
builder.setView(dialogView);
}
Further you need to create a Adapter and inflate your layout for row in the adapter's getView() method and then set that adapter to ListView.
And to handle click events in your listView you can do like this,
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});

Buttons of alert dialog are cut off

I have an alert dialog which is started when someone touches a specific button. The alert dialog contains a view that is defined by a layout xml file. This layout contains several controls like check boxes, edit text fields, ... These controls are all inside a scrool view so that you can scroll through the content, if the whole content doesn't fit on the screen.
The problem is now that when I start this alert dialog, the buttons at the bottom are cut off screen. Altough the scrool bar is working and I can scroll through the content of the alert dialog, the buttons of the alert dialog are sometimes not totally visible.
This means:
Sometimes, all is fine and I can see the buttons of the alert dialog, an sometimes for strange reason, the buttons are cut off. I think it's an issue of the view being to big for the alert dialog and pushing the buttons more down.
For example, the view contains an edit text control. If I enter my name ther, everything is fine. But if I add a new line to this edit text, the buttons start to be cut off a little bit.
What did I wrong? I thought the scroll view would handle the oversize of my view so that the alert dialog fits to the screen.
My app is in portrait mode always.
The code of the view:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/bitteeinstellungenwaehlen" />
<EditText
android:id="#+id/edtTeam1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hteam1"
android:text="Christoph" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/edtTeam2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hteam2"
android:text="Lea" />
<EditText
android:id="#+id/edtTeam3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hteam3"
android:text="Ludwig" />
<EditText
android:id="#+id/edtTeam4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hteam4"
android:text="Anja" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/weitereeinstellungen" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/chkModerationMode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/moderationsmodus" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="#string/info" />
</LinearLayout>
<CheckBox
android:id="#+id/chkPassOver"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="#string/weitergeben" />
<CheckBox
android:id="#+id/chkBlackScreen"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/blankscreen" />
</LinearLayout>
</ScrollView>
And that's how I start the alert dialog:
final AlertDialog.Builder alert = new AlertDialog.Builder(QuizEditor.this);
alert.setTitle(getString(R.string.speichernUndVorschau) + "...");
alert.setMessage("");
LayoutInflater inflater = LayoutInflater.from(QuizEditor.this);
final View layFrage = inflater.inflate(R.layout.layoutquizsettings,null);
alert.setView(layFrage);
final CheckBox chkModeration = (CheckBox) layFrage.findViewById(R.id.chkModerationMode);
final CheckBox chkPassOver = (CheckBox) layFrage.findViewById(R.id.chkPassOver);
final CheckBox chkBlackScreen = (CheckBox) layFrage.findViewById(R.id.chkBlackScreen);
final EditText edtTeam1 = (EditText) layFrage.findViewById(R.id.edtTeam1);
final EditText edtTeam2 = (EditText) layFrage.findViewById(R.id.edtTeam2);
final EditText edtTeam3 = (EditText) layFrage.findViewById(R.id.edtTeam3);
final EditText edtTeam4 = (EditText) layFrage.findViewById(R.id.edtTeam4);
alert.setNeutralButton(getString(R.string.speichernUndVorschau), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.setNegativeButton(getString(R.string.abbrechen), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
final AlertDialog dialog2 = alert.create();
dialog2.setOnShowListener(new OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
// TODO Auto-generated method stub
Button btnStarten = (Button) dialog2.getButton(AlertDialog.BUTTON_NEUTRAL);
btnStarten.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<String> teams = new ArrayList<String>();
String team1 = edtTeam1.getText().toString().trim();
String team2 = edtTeam2.getText().toString().trim();
String team3 = edtTeam3.getText().toString().trim();
String team4 = edtTeam4.getText().toString().trim();
if(team1.length() > 0) teams.add(team1);
if(team2.length() > 0) teams.add(team2);
if(team3.length() > 0) teams.add(team3);
if(team4.length() > 0) teams.add(team4);
if(teams.size() == 0) {
Toast.makeText(QuizEditor.this, getString(R.string.keinteameingegeben), Toast.LENGTH_SHORT).show();
}
else
{
// Quiz starten
dialog2.dismiss();
Intent myIntent;
if(chkBlackScreen.isChecked()) {
myIntent = new Intent(QuizEditor.this, BlackScreen.class);
}
else // Direkt das Quiz starten
{
myIntent = new Intent(QuizEditor.this, Quiz.class);
}
myIntent.putStringArrayListExtra("teams", teams);
myIntent.putExtra("moderation", chkModeration.isChecked());
myIntent.putExtra("passover", chkPassOver.isChecked());
myIntent.putExtra("filename", filename);
QuizEditor.this.startActivity(myIntent);
}
}
});
}
});
dialog2.show();
// dialog2.getWindow().setLayout(LayoutParams.WRAP_CONTENT, 300);
I am sorry for the German words. In the image you can see the problem.
Unfortunately I was not allowed to upload the screenshots I made...
The question was already solved in the comments, but I will add an answer for completeness and to show that it worked for me, too.
For an AlertDialog with a custom view, don't use the .setMessage line. Removing the following line in my project caused the buttons to stop getting clipped.
.setMessage("This is my message")
Set EditText lines to 1. Also set outer LinearLayout's to fill_parent.
Just make all the EditText property android:singleLine="true" and then try to test.

Categories

Resources