Setting a layout for an Android AlertDialog - android

I can create an Android AlertDialog as like this.
AlertDialog.Builder MyDialog = new AlertDialog.Builder(this);
But what matters to me is how can I set a layout for this. When I use a Dialog I can initialize and set a layout as like this.
dialog = new Dialog(Login.this,android.R.style.Theme_Holo_Dialog);
dialog.setContentView(R.layout.journey_details);
can I do something like that to set a layout. Or is in AlertDialog such a functionality not there.
I first created a custom dialog and when I'm setting the time for a text view it gave a null pointer. That's why I tried a AlertDialog. This is my first code. I was unable to figure out the error.
public void ShowJourneyDetails() {
dialog = new Dialog(Login.this,android.R.style.Theme_Holo_Dialog);
crnt_time=(TextView)findViewById(R.id.jd_txt_str_tim);
date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String crnt_date =date.format(new Date()).toString();
crnt_time.setText(crnt_date);
}
This gave me an error. Thats why I tried a AlertDialog.
But my AlterDialog also gives me a NullPointer and the error comes from the button. My code is below
public void ShowJourneyDetails() {
// dialog = new Dialog(Login.this,android.R.style.Theme_Holo_Dialog);
final AlertDialog.Builder MyDialog = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.from(Login.this);
final View DialogView = factory.inflate(R.layout.journey_details, null);
MyDialog.setView(DialogView);
LoginIntent = new Intent(Login.this, DropPickUp_List.class);
check_fuel = (CheckBox) findViewById(R.id.jd_chk_ful);
check_e_oil = (CheckBox) findViewById(R.id.jd_chk_eoil);
check_wtr = (CheckBox) findViewById(R.id.jd_chk_wtr);
check_b_oil = (CheckBox) findViewById(R.id.jd_chk_boil);
check_lic = (CheckBox) findViewById(R.id.jd_chk_lc_inc);
check_gt_pass = (CheckBox) findViewById(R.id.jd_chk_gt_ps);
check_bills = (CheckBox) findViewById(R.id.jd_chk_bil);
crnt_time = (TextView) findViewById(R.id.jd_txt_str_tim);
dialogButton = (Button) dialog.findViewById(R.id.jd_btn_strt);
MyDialog.setView(check_fuel);
MyDialog.setView(check_e_oil);
MyDialog.setView(check_wtr);
MyDialog.setView(check_b_oil);
MyDialog.setView(check_lic);
MyDialog.setView(check_gt_pass);
MyDialog.setView(check_bills);
MyDialog.setView(dialogButton);
MyDialog.setView(crnt_time);
SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String crnt_date = date.format(new Date()).toString();
crnt_time.setText(crnt_date);
final Stack<String> ItemStack=new Stack();
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(Login.this, msg, Toast.LENGTH_LONG).show();
}
});
MyDialog.show();
}
I can't figure out the error.

If you want to create Custom AlertDialog then you need to Inflate Layout Like below:
LayoutInflater factory = LayoutInflater.from(this);
final View dialogView = factory.inflate(
R.layout.custom_progress_layout, null);
and set this Layout to your Dialog like below:
Dialog main_dialog = new Dialog(this, R.style.Theme_Dialog);
main_dialog.setContentView(dialogView);
That's it.

Yes. You can do it this way:
LayoutInflater mLayoutInflator = LayoutInflater.from(this);
final View customDialogView = mLayoutInflator.inflate(
R.layout.journey_details, null);
final AlertDialog customDialog= new AlertDialog.Builder(this).create();
customDialog.setView(customDialogView);
customDialog.show();

You can call
http://developer.android.com/reference/android/app/AlertDialog.html#setView(android.view.View)
on the AlertDialog.

Related

How to access 'findViewById' method inside Dialog onClick event

I'm having a custom layout xml file named login_form with a LinearLayout root named login_form_root. I'm trying to display this layout using dialog but can't get values from EditText as I get cannot resolve method findViewById inside onCreateDialog.
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.login_form, null));
builder.setPositiveButton(okText, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
View myView = inflater.inflate(R.layout.login_form, (ViewGroup) findViewById(R.id.login_form_root));
EditText userEmail = (EditText) myView.findViewById(R.id.email_address);
userEmailValue = userEmail.getText().toString();
Toast.makeText(getActivity(), userEmailValue, Toast.LENGTH_SHORT).show();
}
Error is here:-
"(ViewGroup) findViewById(R.id.login_form_root)"
so how can I inflate the custom layout to get EditText values?
You should save the View when inflate it, then you can use it later
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
final View view = layoutInflater.inflate(R.layout.login_form, null);
builder.setView(view);
AlertDialog dialog = builder.create();
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
EditText userEmail = (EditText) view.findViewById(R.id.email_address);
String userEmailValue = userEmail.getText().toString();
}
});

How to save user input from Alert Dialog?

I'm building an app that is supposed to take text entered from the user and place them into the textviews in a custom list item. The user enters the text into an AlertDialog but once the AlertDialog closes (hence destroyed), all the text entered is destroyed alongside with it and gives me a NullPointerException error.
This is code that handles the Dialog creation and data retrieving:
public class AssignmentActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_assignment);
...
FloatingActionButton assignmentAddButton = (FloatingActionButton) findViewById(R.id.assignment_add_button);
assignmentAddButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editCourseInfoDialog();
}
});
}
private void editCourseInfoDialog() {
LayoutInflater inflater = LayoutInflater.from(AssignmentActivity.this);
View dialogLayout = inflater.inflate(R.layout.assignment_edit_dialog, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(AssignmentActivity.this);
dialog.setView(dialogLayout);
final TextView name = (TextView) dialogLayout.findViewById(R.id.assignmentNameView);
final TextView mark = (TextView) dialogLayout.findViewById(R.id.assignmentMarkView);
final TextView overallMark = (TextView) dialogLayout.findViewById(R.id.assignmentOverallMarkView);
final TextView weight = (TextView) dialogLayout.findViewById(R.id.assignmentWeightView);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
assignment.setName(String.valueOf(name.getText()));
assignment.setMark(Double.valueOf(mark.getText() + ""));
assignment.setMarkOutOf(Double.valueOf(overallMark.getText() + ""));
assignment.setPercentage(Double.valueOf(weight.getText() + ""));
assignmentAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
}
}
The issue with your initialization.
LayoutInflater inflater = LayoutInflater.from(AssignmentActivity.this);
View dialogLayout = inflater.inflate(R.layout.assignment_edit_dialog, null);
AlertDialog.Builder dialog = new AlertDialog.Builder(AssignmentActivity.this);
dialog.setView(dialogLayout);
final TextView name = (TextView) dialogLayout .findViewById(R.id.assignmentNameView);
final TextView mark = (TextView) dialogLayout .findViewById(R.id.assignmentMarkView);
final TextView overallMark = (TextView) dialogLayout .findViewById(R.id.assignmentOverallMarkView);
final TextView weight = (TextView) dialogLayout .findViewById(R.id.assignmentWeightView);
As you said TextViews are hooked up with AlertDialog custom view then they view context should be of Dialog view.
You have a lot to learn in terms of concept. You are setting adapter before initializing your list.
assignmentAdapter = new AssignmentListAdapter(assignmentList, this); // at this line **assignmentList** is null as you initiliaze after this line
assignment = new Assignment(this);
You must initialize first like this
assignment = new Assignment(this);
assignmentAdapter = new AssignmentListAdapter(assignmentList, this);

Android- getChildAt(poisition) produces null

Guys i have a Custom alert dialogue and inside that i am inflating a listView
i want to access the child of that listview but it produces error can anyone help here is my relevant code snippet
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Context);
View alertView = AddExpenses.this.getLayoutInflater().inflate(R.layout.layout_alert_expenses, null);
int amount = Integer.parseInt(etExpensesAmount.getText().toString());
final ListView lvAlertDialogue = (ListView) alertView.findViewById(R.id.lv_alert_expenses);
final TextView tvTotal = (TextView) alertView.findViewById(R.id.tv_amount);
tvTotal.setText(etExpensesAmount.getText().toString());
CustomAdapterAlertList customAdapterAlertList = new CustomAdapterAlertList(AddExpenses.this, listSelectedContact, amount);
lvAlertDialogue.setAdapter(customAdapterAlertList);
alertDialogBuilder.setView(alertView);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
final EditText etAmount;
View singleView = lvAlertDialogue.getChildAt(listSelectedContact.size()-1); //singleView is null here
getChildAt() works for the visible item in list view otherwise it will return null.
Seeing your code I suppose you want the last item. You can try the following code.
View singleView = lvAlertDialog.getChildAt(lvAlertDialog.getLastVisiblePosition()):
In your code you are calling lvAlertDialog.getChildAt(lvAlertDialog.getLastVisiblePosition())
just after the alertDialog.show();
getChildAt is excuteing before showing alertDialog and
getChildAt will work if and only if the dialog is visible.
so it is null.
Try this code. Hope It will work.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(Context);
View alertView = AddExpenses.this.getLayoutInflater().inflate(R.layout.layout_alert_expenses, null);
int amount = Integer.parseInt(etExpensesAmount.getText().toString());
final ListView lvAlertDialogue = (ListView) alertView.findViewById(R.id.lv_alert_expenses);
final TextView tvTotal = (TextView) alertView.findViewById(R.id.tv_amount);
tvTotal.setText(etExpensesAmount.getText().toString());
CustomAdapterAlertList customAdapterAlertList = new CustomAdapterAlertList(AddExpenses.this, listSelectedContact, amount);
lvAlertDialogue.setAdapter(customAdapterAlertList);
alertDialogBuilder.setView(alertView);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
View singleView = lvAlertDialogue.getChildAt(listSelectedContact.size() - 1); //singleView is null here
}
});
alertDialog.show();

AlertDialog.Builder with custom layout and EditText; cannot access view

I am trying to create an alert dialog with an EditText object. I need to set the initial text of the EditText programmatically. Here's what I have.
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
AlertDialog alertDialog = dialogBuilder.create();
LayoutInflater inflater = this.getLayoutInflater();
alertDialog.setContentView(inflater.inflate(R.layout.alert_label_editor, null));
EditText editText = (EditText) findViewById(R.id.label_field);
editText.setText("test label");
alertDialog.show();
What do I need to change so that I can have a valid EditText object?
[edit]
So, it was pointed out by user370305 and others that I should be using alertDialog.findViewById(R.id.label_field);
Unfortunately there is another issue here. Apparently, setting the content view on the AlertDialog causes the program to crash at runtime. You have to set it on the builder.
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));
AlertDialog alertDialog = dialogBuilder.create();
LayoutInflater inflater = this.getLayoutInflater();
EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);
editText.setText("test label");
alertDialog.show();
Unfortunately, when you do this, alertDialog.findViewById(R.id.label_field); now returns null.
[/edit]
editText is a part of alertDialog layout so Just access editText with reference of alertDialog
EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);
Update:
Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));
inflater is Null.
update your code like below, and try to understand the each code line
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
Update 2:
As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId) method of AlertDialog.Builder class, which is available from API 21 and onwards.
Use this one
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
// Get the layout inflater
LayoutInflater inflater = (activity).getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the
// dialog layout
builder.setTitle(title);
builder.setCancelable(false);
builder.setIcon(R.drawable.galleryalart);
builder.setView(inflater.inflate(R.layout.dialogue, null))
// Add action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
}
});
builder.create();
builder.show();
You can write:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView= inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
Button button = (Button)dialogView.findViewById(R.id.btnName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Commond here......
}
});
EditText editText = (EditText)
dialogView.findViewById(R.id.label_field);
editText.setText("test label");
dialogBuilder.create().show();
In case any one wants it in Kotlin :
val dialogBuilder = AlertDialog.Builder(this)
// ...Irrelevant code for customizing the buttons and title
val dialogView = layoutInflater.inflate(R.layout.alert_label_editor, null)
dialogBuilder.setView(dialogView)
val editText = dialogView.findViewById(R.id.label_field)
editText.setText("test label")
val alertDialog = dialogBuilder.create()
alertDialog.show()
Reposted #user370305's answer.
Change this:
EditText editText = (EditText) findViewById(R.id.label_field);
to this:
EditText editText = (EditText) v.findViewById(R.id.label_field);
View v=inflater.inflate(R.layout.alert_label_editor, null);
alertDialog.setContentView(v);
EditText editText = (EditText)v.findViewById(R.id.label_field);
editText.setText("test label");
alertDialog.show();
/**
* Shows confirmation dialog about signing in.
*/
private void startAuthDialog() {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
alertDialog.getWindow().setLayout(800, 1400);
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.auth_dialog, null);
alertDialog.getWindow().setContentView(dialogView);
EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
}
Try making View final
eg:(with custom layout)
final View layout=getLayoutInflater().inflate(R.layout.create_class,null);
builder.setView(layout);

Help with creating a dialog and passing info to it

I have created a screen with 5 rows of information. each row has 2 values. (value1 and value2)
At the end of each row is a button. For each row I have created a xml file that I am looping though and filling in the values from a database
what I am looking at doing is when the button is pressed a dialog is opened with two editviews filled in with the values from that row
Then when the button is pressed on the dialog the values are updated in database.
I am having problems with the createdialog / preparedialog methods and passing the values to them.
UPDATE with Code
public void createLayout(LinearLayout pMainlayout, String pMajorValue) {
DatabaseTools db = new DatabaseTools(this);
majorValue= pMajorValue;
nameInfo = db.getNames(pMajorValue);
name = returnName(pMajorValue);
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < nameInfo.size(); i++) {
// Get views
View view = (View) inflater.inflate(R.layout.mainlayout, null);
TextView nameView = (TextView) sightmarkView.findViewById(R.id.name_title);
TextView Value1View = (TextView) sightmarkView.findViewById(R.id.value1);
TextView ValueView = (TextView) sightmarkView.findViewById(R.id.value2);
Button updateButton = (Button) sightmarkView.findViewById(R.id.updatebutton);
// Get info from Database
nameValue = nameInfo.get(i).toString();
value1v = db.getMark(majorValue, nameInfo.get(i).toString());
value2v = db.getMark(majorValue, nameInfo.get(i).toString());
// populate info into fields
nameView.setText(nameValue);
Value1View.setText(String.valueOf(value1));
Value2View.setText(String.valueOf(value2));
updateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Bundle bundle = new Bundle();
//Code here to add values to a bundle
showDialog(SIGHTMARK_DIALOG_ID, bundle);
}
});
pMainlayout.addView(view);
}
}
All this work correctly. The values are displayed. I have looked into using a bundle to pass them into the dialog
#Override
protected Dialog onCreateDialog(int id, Bundle bundle) {
switch(id) {
case DIALOG_ID:
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View layout = inflater.inflate(R.layout.update, (ViewGroup) findViewById(R.id.update));
final EditText value1Edit = (EditText) layout.findViewById(R.id.value1_current);
final EditText value2Edit = (EditText) layout.findViewById(R.id.value2_current);
//next pull values from bundle to populate into fields
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(layout);
// Now configure the AlertDialog
builder.setTitle(R.string.sight_update_title);
builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
this.removeDialog(DIALOG_ID);
}
});
builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
value1New = Float.parseFloat(value1Edit.getText().toString());
value2New = Float.parseFloat(value2Edit.getText().toString());
// method run to update the database with the new values passed to it
updateMarks(value1, value2);
this.removeDialog(DIALOG_ID);
}
});
// Create the AlertDialog and return it
AlertDialog Dialog = builder.create();
return Dialog;
}
return null;
}
This part has issues and is not getting the values correctly or passing them to the update method
i think the problem is here:
If you use showDialog(int), the activity will call through to this
method the first time, and hang onto it thereafter. Any dialog that is
created by this method will automatically be saved and restored for
you, including whether it is showing.
remove references
removeDialog(SIGHTMARK_DIALOG_ID);
showDialog(SIGHTMARK_DIALOG_ID, bundle);
documentation

Categories

Resources