AlertDialogs setCustomTitle not working with android.support.v7.app.AlertDialog - android

I want to customize TITLE color of V7 AlertDialog. SetCustomTitle() doesnt seems to be working with android.support.v7.app.AlertDialog. I can see a blank TITLE like below
But expected AlertDialog is below
Creating Alert Dialog
private void createDialog() {
ContextThemeWrapper ctw = new ContextThemeWrapper( mContext, R.style.TooltipTheme);
AlertDialog.Builder builder = new CustomAlertDialogBuilder(ctw);
builder.setTitle(mTitle);
builder.setMessage(mMsg);
builder.setPositiveButton(mOkButton,null);
AlertDialog alert11 = builder.create();
alert11.show();
Button positiveButton = alert11.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setTextColor(mContext.getResources().getColor(R.color.BNPP_Color_Palette_PrimaryBtn));
}
style.xml
<style name="TooltipTheme" parent="Theme.AppCompat.Dialog.Alert"></style>
CustomAlertDialogBuilder
public class CustomAlertDialogBuilder extends AlertDialog.Builder {
private final Context mContext;
private TextView mTitle;
private ImageView mIcon;
private TextView mMessage;
public CustomAlertDialogBuilder(Context context) {
super(context);
mContext = context;
View customTitle = View.inflate(mContext, R.layout.alert_dialog_title, null);
mTitle = (TextView) customTitle.findViewById(R.id.alertTitle);
mIcon = (ImageView) customTitle.findViewById(R.id.icon);
setCustomTitle(customTitle);
View customMessage = View.inflate(mContext, R.layout.alert_dialog_message, null);
mMessage = (TextView) customMessage.findViewById(R.id.message);
setView(customMessage);
}
#NonNull
#Override
public AlertDialog.Builder setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener) {
return super.setPositiveButton(text, listener);
}
#NonNull
#Override
public AlertDialog.Builder setPositiveButton(int textId, DialogInterface.OnClickListener listener) {
return super.setPositiveButton(textId, listener);
}
#Override
public CustomAlertDialogBuilder setTitle(int textResId) {
mTitle.setText(textResId);
return this;
}
#Override
public CustomAlertDialogBuilder setTitle(CharSequence text) {
mTitle.setText(text);
return this;
}
#Override
public CustomAlertDialogBuilder setMessage(int textResId) {
mMessage.setText(textResId);
return this;
}
#Override
public CustomAlertDialogBuilder setMessage(CharSequence text) {
mMessage.setText(text);
return this;
}
#Override
public CustomAlertDialogBuilder setIcon(int drawableResId) {
mIcon.setImageResource(drawableResId);
return this;
}
#Override
public CustomAlertDialogBuilder setIcon(Drawable icon) {
mIcon.setImageDrawable(icon);
return this;
}
}

You could disable the standard title with
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
and through
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
Have a view with custom title.

Related

List refreshed withous notifyDataSetChange?

I have a little question for you. I have an app which displays a list of subjects which could be removed or addedd. During developing I realized that I could add new subject without call notifyDataSetChange, why?
Class (ListSubject) which manage list of subjects:
public static ListView mListView;
private Context mContext;
List<Subject> data;
SubjectAdapter subjectSubjectAdapter;
public ListSubject(Context mContext) {
this.mContext = mContext;
}
public List<Subject> populateList() {
DBManager db = new DBManager(mContext);
data = db.GetSubjects();
return data;
}
public void DeleteAll(){
DBManager db = new DBManager(mContext);
db.ClearTable("TBLSUBJECTS");
data.clear();
}
public void AddSubject(String name, int frequency){
DBManager db = new DBManager(mContext);
Subject subToAdd = db.InsertSubject(name, frequency);
data.add(subToAdd);
}
public void DeleteSubject(int id){
DBManager db = new DBManager(mContext);
db.DeleteSubject(id);
}
}
Class (ListSubjectActivity) which rappresents the activity where is listview:
DBManager db;
Button btnClearSubjectTable;
Button btnAddSub;
Context mContext;
private List<Subject> mListSubject;
private SubjectAdapter subjectAdapter;
private ListView lvSubject;
private ListSubject ls;
public ListSubjectActivity(Context mContext) {
this.mContext = mContext;
}
public ListSubjectActivity(){}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_subject);
db = new DBManager(this);
btnClearSubjectTable = (Button) findViewById(R.id.btnClearSubjectTable);
btnAddSub = (Button) findViewById(R.id.btnAddSubject);
lvSubject = (ListView)findViewById(R.id.subjectList);
mListSubject = new ArrayList<>();
ls = new ListSubject(getApplicationContext());
mListSubject = ls.populateList();
btnClearSubjectTable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ls.DeleteAll();
subjectAdapter.notifyDataSetChanged();
}
});
btnAddSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Dialog dialog = new Dialog(ListSubjectActivity.this);
dialog.setContentView(R.layout.dialog_insert_subject);
final EditText txtNewSubName = (EditText) dialog.findViewById(R.id.txtNewSubName);
final EditText txtFreqNewSub = (EditText) dialog.findViewById(R.id.txtFreqNewSub);
Button dialogButtonOK = (Button) dialog.findViewById(R.id.btnOK);
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddSubject(txtNewSubName.getText().toString(), Integer.parseInt(txtFreqNewSub.getText().toString()));
subjectAdapter.notifyDataSetChanged();
dialog.dismiss();
}
});
Button dialogButtonCancel = (Button) dialog.findViewById(R.id.btnCancel);
dialogButtonCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
Window window = dialog.getWindow();
window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, 700);
}
});
subjectAdapter = new SubjectAdapter(getApplicationContext(), mListSubject);
lvSubject.setAdapter(subjectAdapter);
}
public void AddSubject(String newSub, int frequency)
{
ls.AddSubject(newSub, frequency);
}
My subject adapter:
private Context mContext;
private List<Subject> mList;
private ListSubject ls;
public SubjectAdapter(Context mContext, List<Subject> mList) {
this.mContext = mContext;
this.mList = mList;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = View.inflate(mContext, R.layout.item_subject_list,null);
TextView txtSubjectName = v.findViewById(R.id.txtName);
TextView txtFrequency = v.findViewById(R.id.txtFrequency);
txtSubjectName.setText(mList.get(position).GetSubjectName());
txtFrequency.setText(Integer.toString(mList.get(position).GetFrequency()));
ls = new ListSubject(mContext);
ImageButton btnDeleteSub = (ImageButton) v.findViewById(R.id.btnDeleteSub);
btnDeleteSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ls.DeleteSubject(mList.get(position).GetSubjectID());
mList.remove(position);
notifyDataSetChanged(); useless
}
});
return v;
}
}
Keep in mind please, that I'm new in android development so could be make a lot of mistake. Thank you who help me
If your current code is what you're wondering about, you are calling notifyDataSetChanged() when adding an item. It's right here:
Button dialogButtonOK = (Button) dialog.findViewById(R.id.btnOK);
dialogButtonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddSubject(txtNewSubName.getText().toString(), Integer.parseInt(txtFreqNewSub.getText().toString()));
subjectAdapter.notifyDataSetChanged(); //see?
dialog.dismiss();
}
});

Change Imageview of Alertdialog as per the result

I want to develop the UI in which user will touch the touch pad and if he is registered user of the system , he will be verified by my app. So to indicate that I want to change the fingerprint image by green (valid user) , red (invalid user). So I have created the fragment in which I am getting that result in following two methods
#Override
public void authenticate() {
Log.d(TAG, "authoticate: ");
result = "Yes";
//customBuilder.setImage(R.drawable.ic_fingerprint_pressed);//tried but not working
}
#Override
public void errorAuthenticate() {
Log.d(TAG, "fail: ");
result = "No";
// customBuilder.setImage(R.drawable.ic_fingerprint_pressed_error);//tried but not working
}
Now in same fragment I have created the CustomDialog to show the above images which will be change dynamically. Code for CustomDialog class is given below
public class CustomDialog extends AlertDialog {
public CustomDialog(Context context, int theme) {
super(context, theme);
}
public CustomDialog(Context context) {
super(context);
}
/**
* Helper class for creating a custom dialog
*/
public static class Builder {
private Context context;
private String title;
private int res;
private String message;
private String positiveButtonText;
private String negativeButtonText;
private View contentView;
private DialogInterface.OnClickListener
positiveButtonClickListener,
negativeButtonClickListener;
public Builder(Context context) {
this.context = context;
}
public Builder setMessage(String message) {
this.message = message;
return this;
}
public Builder setMessage(int message) {
this.message = (String) context.getText(message);
return this;
}
/**
* Set the Dialog title from resource
* #param title
* #return
*/
public Builder setTitle(int title) {
this.title = (String) context.getText(title);
return this;
}
/**
* Set the Dialog title from String
* #param title
* #return
*/
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setImage(int res){
this.res = res;
return this;
}
/**
* Set a custom content view for the Dialog.
* If a message is set, the contentView is not
* added to the Dialog...
* #param v
* #return
*/
public Builder setContentView(View v) {
this.contentView = v;
return this;
}
/**
* Set the positive button resource and it's listener
* #param positiveButtonText
* #param listener
* #return
*/
public Builder setPositiveButton(int positiveButtonText,
DialogInterface.OnClickListener listener) {
this.positiveButtonText = (String) context
.getText(positiveButtonText);
this.positiveButtonClickListener = listener;
return this;
}
/**
* Set the positive button text and it's listener
* #param positiveButtonText
* #param listener
* #return
*/
public Builder setPositiveButton(String positiveButtonText,
DialogInterface.OnClickListener listener) {
this.positiveButtonText = positiveButtonText;
this.positiveButtonClickListener = listener;
return this;
}
/**
* Set the negative button resource and it's listener
* #param negativeButtonText
* #param listener
* #return
*/
public Builder setNegativeButton(int negativeButtonText,
DialogInterface.OnClickListener listener) {
this.negativeButtonText = (String) context
.getText(negativeButtonText);
this.negativeButtonClickListener = listener;
return this;
}
/**
* Set the negative button text and it's listener
* #param negativeButtonText
* #param listener
* #return
*/
public Builder setNegativeButton(String negativeButtonText,
DialogInterface.OnClickListener listener) {
this.negativeButtonText = negativeButtonText;
this.negativeButtonClickListener = listener;
return this;
}
/**
* Create the custom dialog
*/
public CustomDialog create() {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// instantiate the dialog with the custom Theme
final CustomDialog dialog = new CustomDialog(context,
R.style.Dialog);
View layout = inflater.inflate(R.layout.capture_finger_touch, null);
// dialog.addContentView(layout, new ViewGroup.LayoutParams(
// ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
// set the dialog title
((ImageView) layout.findViewById(R.id.imgView)).setImageResource(res);
// set the confirm button
if (positiveButtonText != null) {
((Button) layout.findViewById(R.id.btn))
.setText(positiveButtonText);
if (positiveButtonClickListener != null) {
((Button) layout.findViewById(R.id.btn))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
positiveButtonClickListener.onClick(
dialog,
DialogInterface.BUTTON_POSITIVE);
}
});
}
} else {
// if no confirm button just set the visibility to GONE
layout.findViewById(R.id.btn).setVisibility(
View.GONE);
}
dialog.setView(layout);
return dialog;
}
}
}
And I have used above CustomDialog by following way
public static String result = "No Found";
CustomDialog.Builder customBuilder = new CustomDialog.Builder(getActivity());
public void captureFingerPrintTouchCustom() {
if (result.equalsIgnoreCase("Yes")) {
customBuilder.setImage(R.drawable.ic_fingerprint_pressed);
} else if (result.equalsIgnoreCase("No")) {
customBuilder.setImage(R.drawable.ic_fingerprint_pressed_error);
//rl.startAnimation(animation);
} else customBuilder.setImage(R.drawable.ic_fingerprint_for_capture);
customBuilder.setPositiveButton("OK2", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog = customBuilder.create();
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.show();
}
Here as per the result value I want to change the image of customdialog.
capture_finger_touch.xml code is given below
<?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">
<RelativeLayout
android:id="#+id/rl"
android:layout_width="#dimen/alert_dialog_size"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/rounded_white_background"
android:padding="#dimen/view_internal_space">
<ImageView
android:id="#+id/imgView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="#drawable/key_bg_square"
android:src="#drawable/ic_fingerprint_for_capture" />
<Button
android:id="#+id/btn"
style="#style/button_style"
android:layout_height="#dimen/btnHeight"
android:layout_width="wrap_content"
android:layout_below="#+id/imgView"
android:layout_centerHorizontal="true"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:textColor="#color/white"
android:textSize="#dimen/BTC_title_size"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
But problem is that its not changing the image dynamically. CustomDialog is created like this,
I would suggest you to extend DialogFragment.class, inflate there you layout and communicate with it in you Activity or Fragment
public class FingerprintDialog extends AppCompatDialogFragment implements View.OnClickListener {
private DialogFingerprintBinding binding;
private Listener listener;
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (Listener) context;
} catch (ClassCastException e) {
throw new ClassCastException(context.toString() + " implement Listener");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//if you use databinding
//binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.XXX, null, false);
//binding.buttonCancel.setOnClickListener(this);
View view = inflater.inflate(R.layout.XXX, container, false);
Button button = view.findViewById(R.id.button);
getDialog().setCanceledOnTouchOutside(false);
if (getDialog().getWindow() != null) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
//return binding.getRoot(); for binding
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button:
listener.cancel();
break;
default:
break;
}
}
public void changeImage(//posible resource) {
//change Image here
}
public interface Listener {
void cancel();
}
}
And then create instance of this dialog nad show it using method DialogFragment#show
You need to setImageResource to ImageView as follows:
private fingerPrintImageView;
public CustomDialog create() {fingerPrintImageView = ((ImageView) layout.findViewById(R.id.imgView)).setImageResource(res);}
public Builder setImage(int res){this.res = res;fingerPrintImageView.setImageResource(res); return this;}

Floating Context Menu RecyclerView

Here,
they is very little to find about adding a Floating Context Menu to RecyclerView items and a lot of different informations. I want one single context menu button and I have implemented it this way:
itemView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuItem delete = menu.add(0, v.getId(), 0, "Delete");
delete.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int position = getAdapterPosition();
long id = mUploads.get(position).getId();
if (position != RecyclerView.NO_POSITION) {
mListener.onDeleteClick(position, id);
}
return true;
}
});
}
});
This then calls this interface method:
#Override
public void onDeleteClick(int position, long id) {
Toast.makeText(this, "position: " + position + " ID: " + id, Toast.LENGTH_SHORT).show();
}
However, this all looks very messy and I wonder if that approach will lead to problems later.
I use custom dialogs quite often so I use DialogFragment. Note this dialog has an "Ok" and "Cancel" buttons. You can remove the buttons if you do not need them.
You need to create an XML Layout for the Custom DialogFragment "fragment_submit_cancel_dialog". The ability to create your own design gives you a great deal of flexibility in the appearance of your dialog. Here is a simple example, but it can be modified as you need - even add images or lists.
<?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">
<TextView
android:id="#+id/tvTitle"
android:text="Title"
style="#style/alert_dialog_title"
/>
<TextView
android:id="#+id/tvMessage"
android:text="MyMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_below="#id/tvTitle"
android:layout_centerInParent="true"
android:layout_marginTop="15dp"
/>
</RelativeLayout>
In the Activity you call the DialogFragment you will need to add this:
implements OkCancelDialogFragment.OkCancelDialogListener{
and add the listener method:
#Override
public void onFinishOkCancelDialog(boolean submit) {
if(submit){
// Do what you need here
}
}
Call the DialogFragment like this:
private void startOkDialog(){
String title = "What ever you want as a Title";
String mess = "Your Message!";
OkCancelDialogFragment dialog = OkCancelDialogFragment.newInstance(title, mess);
show(getFragmentManager(), "OkDialogFragment");
}
Now the code for the Custom Dialog Fragment:
public class OkCancelDialogFragment extends DialogFragment {
private static final String ARG_TITLE = "title";
private static final String ARG_MESSAGE = "message";
Context context = null;
private String title;
private String message;
private boolean submitData = false;
private OkCancelDialogListener mListener;
public OkCancelDialogFragment() {
}
public static OkCancelDialogFragment newInstance(String title, String message) {
OkCancelDialogFragment fragment = new OkCancelDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_TITLE, title);
args.putString(ARG_MESSAGE, message);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
title = getArguments().getString(ARG_TITLE);
message = getArguments().getString(ARG_MESSAGE);
}
}
#Override
public Dialog onCreateDialog(Bundle saveIntsanceState){
context = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View rootView = inflater.inflate(R.layout.fragment_submit_cancel_dialog, null, false);
final TextView titleView = (TextView)rootView.findViewById(R.id.tvTitle);
final TextView messView = (TextView)rootView.findViewById(R.id.tvMessage);
titleView.setText(title);
messView.setText(message);
builder.setView(rootView)
.setPositiveButton(R.string.button_Ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
submitData = true;
//The onDetach will call the Listener! Just in case the user taps the back button
}
})
.setNegativeButton(R.string.button_cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
submitData = false;
}
});
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if(mListener == null) mListener = (OkCancelDialogListener) context;
}
catch (Exception ex){
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener.onFinishOkCancelDialog(submitData);
mListener = null;
}
public interface OkCancelDialogListener {
void onFinishOkCancelDialog(boolean submit);
}
}
If you have any questions about how this is implement just let me know.

trouble with View or something in Android

I am currently in trouble with my project.
I am trying to separate functions into different classes instead of putting all in Activity class.
So I think I need to pass "view" from SettingsActivity to ConfigPresenter, from ConfigPresenter to ConfigEventHandler.
but I don not know why it doesn't work at all.
can anyone help me to know what the problem is?
Appreciate all the time and sorry that I only come stackoverflow to get information.
I hope I become a professional someday and help people here. :)
I make errors bold below.
SettingsActivity.java
- configPresenter.optionClicked **(view)**
ConfigPresenter.java
- eh.checkOption **(view)**
ConfigEventHandler.java
- AlertDialog.Builder builder = new AlertDialog.Builder **(SettingsActivity.class)**
- LayoutInflater inflater = SettingsActivity.class.**getLayoutInflater()**
- TextView titleUrl = (TextView) **findViewById**(title);
- TextView optionUrl = (TextView) **findViewById**(option);
SettingsActivity.java
public class SettingsActivity extends AppCompatActivity implements ConfigPresenter.View {
private ConfigPresenter configPresenter;
private Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
public void optionClicked(View view) {
configPresenter.optionClicked(view);
}
}
ConfigPresenter.java
public class ConfigPresenter {
private View view;
private ConfigEventHandler eh;
private ConfigFileHandler fh;
public ConfigPresenter(ConfigPresenter.View view) {
this.view = view;
eh = new ConfigEventHandler();
fh = new ConfigFileHandler();
}
public void optionClicked(View view) {
eh.checkOption(view);
Log.d("Config", "Presenter");
}
}
ConfigEventHandler.java
public class ConfigEventHandler {
public void checkOption(View view) {
if ( view.getId() == R.id.layout_url ) {
showDialog(R.id.title_url, R.id.option_url);
} else if ( view.getId() == R.id.layout_port ) {
showDialog(R.id.title_port, R.id.option_port);
} else {
showDialog(R.id.title_path, R.id.option_path);
}
}
public void showDialog(int title, int option) {
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.class);
LayoutInflater inflater = SettingsActivity.class.getLayoutInflater();
View content = inflater.inflate(R.layout.dialog, null);
builder.setView(content);
TextView titleUrl = (TextView) findViewById(title);
TextView dialogTitle = (TextView) content.findViewById(R.id.dialog_title);
TextView optionUrl = (TextView) findViewById(option);
EditText dialogOption = (EditText) content.findViewById(R.id.dialog_option);
dialogTitle.setText(titleUrl.getText());
dialogOption.setText(optionUrl.getText());
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// ok
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel
}
})
.show();
}
}
First of all, your classes aren't logical, but a few fixes for your current setup.
public class SettingsActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setcontentview etc.
}
public void optionClicked(View view){
ConfigPresenter.optionClicked(view,getLayoutInflater(),this);
}
}
ConfigPresenter
public class ConfigPresenter {
public static void optionClicked(View view, LayoutInflater inflater, Context context){
ConfigEventHandler.checkOption(view,inflater,context);
}
}
ConfigEventHandler
public class ConfigEventHandler {
public static void checkOption(View view, LayoutInflater inflater, Context context){
showDialog(inflater,context);
}
private static void showDialog(LayoutInflater inflater, Context context){
AlertDialog dialog = new AlertDialog.Builder(context).create();
View content = inflater.inflate(R.layout.alert_add_item,null);
dialog.setContentView(content);
dialog.show();
}
}
In SettingsActivity:
private ConfigPresenter configPresenter;
private Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
// Initialize configPresenter:
configPresenter = new ConfigPresenter(this)
}
And in the constructor method in ConfigPresenter, you can remove the weird ConfigPresenter.View like this:
public class ConfigPresenter {
private ConfigEventHandler eh;
private ConfigFileHandler fh;
private Context context;
public ConfigPresenter(Context context) {
this.context = context;
eh = new ConfigEventHandler(context);
fh = new ConfigFileHandler();
}
/* ... */
}
EDIT:The Context also needs to be passed down. Edited code above, and the edits below also needs to be added.
public class ConfigEventHandler {
private Context context;
// Constructor with Context
public ConfigEventHandler(Context context) {
this.context = context;
}
/* ... */
public void showDialog(int title, int option) {
// Passing the context to the Builder:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
/* ... */
}
However - this approach seems to only cause a lot of headache. Why do you want to split up your code in so many classes?

AlerDialog call from other class

I'm trying to call my alertdialog from another class in same file. Where do i have wrong here? Just trying to extends the AlertDialog, but i'm not sure how to do this, i don't want to be in my public main class, trying that and work but i need to be in separable class if this is possible.
class MyDialog extends AlertDialog {
public static Context context;
public static int theme;
protected MyDialog(Context context, int theme) {
super(context, theme);
MyDialog.context = context;
theme = THEME_HOLO_DARK;
MyDialog.theme = theme;
}
public void onCreateAlertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("Auto Start")
.setMessage("Start playing after: 30 sec")
.setIcon(R.drawable.info)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Toast.makeText(context, "Auto start cancaled!", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
}
);
alertDialog.show();
}
}
I call it from main class like this:
Context context = MyDialog.context;
int i = MyDialog.theme;
MyDialog md = new MyDialog(context, i);
md.onCreateAlertDialog();
I think that it comes from the context variable that you didn't initialize it.
You should get it from the activity your are calling the dialog from :
class MyActivity extends Activity{
...
Context context = this;
MyDialog md = new MyDialog(context, i);
...
}
You are using AlertDialog.Builder which will always return an instance of the AlertDialog class when you build it. You would have to override the static builder to return an instance of your class but this is not really possible.
What you want to do is extend the Dialog class and create your own AlertDialog implementation as demonstrated in the HoloEverywhere library.
https://github.com/ChristopheVersieux/HoloEverywhere/blob/master/library/src/com/WazaBe/HoloEverywhere/app/AlertDialog.java
public class AlertDialog extends Dialog implements DialogInterface {
public static class Builder {
private final AlertController.AlertParams P;
public Builder(Context context) {
this(context, resolveDialogTheme(context, 0));
}
public Builder(Context context, int theme) {
P = new AlertController.AlertParams(new ContextThemeWrapper(
context, resolveDialogTheme(context, theme)));
P.mTheme = theme;
}
public AlertDialog create() {
final AlertDialog dialog = new AlertDialog(P.mContext, P.mTheme);
P.apply(dialog.mAlert);
dialog.setCancelable(P.mCancelable);
if (P.mCancelable) {
dialog.setCanceledOnTouchOutside(true);
}
dialog.setOnCancelListener(P.mOnCancelListener);
if (P.mOnKeyListener != null) {
dialog.setOnKeyListener(P.mOnKeyListener);
}
return dialog;
}
public Context getContext() {
return P.mContext;
}
public Builder setAdapter(final ListAdapter adapter,
final OnClickListener listener) {
P.mAdapter = adapter;
P.mOnClickListener = listener;
return this;
}
public Builder setCancelable(boolean cancelable) {
P.mCancelable = cancelable;
return this;
}
public Builder setCheckedItem(int checkedItem) {
P.mCheckedItem = checkedItem;
return this;
}
public Builder setCursor(final Cursor cursor,
final OnClickListener listener, String labelColumn) {
P.mCursor = cursor;
P.mLabelColumn = labelColumn;
P.mOnClickListener = listener;
return this;
}
public Builder setCustomTitle(View customTitleView) {
P.mCustomTitleView = customTitleView;
return this;
}
public Builder setIcon(Drawable icon) {
P.mIcon = icon;
return this;
}
public Builder setIcon(int iconId) {
P.mIconId = iconId;
return this;
}
public Builder setIconAttribute(int attrId) {
TypedValue out = new TypedValue();
P.mContext.getTheme().resolveAttribute(attrId, out, true);
P.mIconId = out.resourceId;
return this;
}
public Builder setInverseBackgroundForced(boolean useInverseBackground) {
P.mForceInverseBackground = useInverseBackground;
return this;
}
public Builder setItems(CharSequence[] items,
final OnClickListener listener) {
P.mItems = items;
P.mOnClickListener = listener;
return this;
}
public Builder setItems(int itemsId, final OnClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnClickListener = listener;
return this;
}
public Builder setMessage(CharSequence message) {
P.mMessage = message;
return this;
}
public Builder setMessage(int messageId) {
P.mMessage = P.mContext.getText(messageId);
return this;
}
public Builder setMultiChoiceItems(CharSequence[] items,
boolean[] checkedItems,
final OnMultiChoiceClickListener listener) {
P.mItems = items;
P.mOnCheckboxClickListener = listener;
P.mCheckedItems = checkedItems;
P.mIsMultiChoice = true;
return this;
}
public Builder setMultiChoiceItems(Cursor cursor,
String isCheckedColumn, String labelColumn,
final OnMultiChoiceClickListener listener) {
P.mCursor = cursor;
P.mOnCheckboxClickListener = listener;
P.mIsCheckedColumn = isCheckedColumn;
P.mLabelColumn = labelColumn;
P.mIsMultiChoice = true;
return this;
}
public Builder setMultiChoiceItems(int itemsId, boolean[] checkedItems,
final OnMultiChoiceClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnCheckboxClickListener = listener;
P.mCheckedItems = checkedItems;
P.mIsMultiChoice = true;
return this;
}
public Builder setNegativeButton(CharSequence text,
final OnClickListener listener) {
P.mNegativeButtonText = text;
P.mNegativeButtonListener = listener;
return this;
}
public Builder setNegativeButton(int textId,
final OnClickListener listener) {
P.mNegativeButtonText = P.mContext.getText(textId);
P.mNegativeButtonListener = listener;
return this;
}
public Builder setNeutralButton(CharSequence text,
final OnClickListener listener) {
P.mNeutralButtonText = text;
P.mNeutralButtonListener = listener;
return this;
}
public Builder setNeutralButton(int textId,
final OnClickListener listener) {
P.mNeutralButtonText = P.mContext.getText(textId);
P.mNeutralButtonListener = listener;
return this;
}
public Builder setOnCancelListener(OnCancelListener onCancelListener) {
P.mOnCancelListener = onCancelListener;
return this;
}
public Builder setOnItemSelectedListener(
final AdapterView.OnItemSelectedListener listener) {
P.mOnItemSelectedListener = listener;
return this;
}
public Builder setOnKeyListener(OnKeyListener onKeyListener) {
P.mOnKeyListener = onKeyListener;
return this;
}
public Builder setOnPrepareListViewListener(
OnPrepareListViewListener listener) {
P.mOnPrepareListViewListener = listener;
return this;
}
public Builder setPositiveButton(CharSequence text,
final OnClickListener listener) {
P.mPositiveButtonText = text;
P.mPositiveButtonListener = listener;
return this;
}
public Builder setPositiveButton(int textId,
final OnClickListener listener) {
P.mPositiveButtonText = P.mContext.getText(textId);
P.mPositiveButtonListener = listener;
return this;
}
public Builder setRecycleOnMeasureEnabled(boolean enabled) {
P.mRecycleOnMeasure = enabled;
return this;
}
public Builder setSingleChoiceItems(CharSequence[] items,
int checkedItem, final OnClickListener listener) {
P.mItems = items;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(Cursor cursor, int checkedItem,
String labelColumn, final OnClickListener listener) {
P.mCursor = cursor;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mLabelColumn = labelColumn;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(int itemsId, int checkedItem,
final OnClickListener listener) {
P.mItems = P.mContext.getResources().getTextArray(itemsId);
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setSingleChoiceItems(ListAdapter adapter,
int checkedItem, final OnClickListener listener) {
P.mAdapter = adapter;
P.mOnClickListener = listener;
P.mCheckedItem = checkedItem;
P.mIsSingleChoice = true;
return this;
}
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}
public Builder setTitle(int titleId) {
P.mTitle = P.mContext.getText(titleId);
return this;
}
public Builder setView(View view) {
P.mView = view;
P.mViewSpacingSpecified = false;
return this;
}
public Builder setView(View view, int viewSpacingLeft,
int viewSpacingTop, int viewSpacingRight, int viewSpacingBottom) {
P.mView = view;
P.mViewSpacingSpecified = true;
P.mViewSpacingLeft = viewSpacingLeft;
P.mViewSpacingTop = viewSpacingTop;
P.mViewSpacingRight = viewSpacingRight;
P.mViewSpacingBottom = viewSpacingBottom;
return this;
}
public AlertDialog show() {
AlertDialog dialog = create();
dialog.show();
return dialog;
}
}
public static final int THEME_HOLO_DARK = 1;
public static final int THEME_HOLO_LIGHT = 2;
static int resolveDialogTheme(Context context, int resid) {
if (resid == THEME_HOLO_DARK) {
return R.style.Holo_Theme_Dialog_Alert;
} else if (resid == THEME_HOLO_LIGHT) {
return R.style.Holo_Theme_Dialog_Alert_Light;
} else if (resid >= 0x01000000) {
return resid;
} else {
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.alertDialogTheme,
outValue, true);
return outValue.resourceId;
}
}
private final AlertController mAlert;
protected AlertDialog(Context context) {
this(context, false, null, resolveDialogTheme(context, 0));
}
protected AlertDialog(Context context, boolean cancelable,
OnCancelListener cancelListener) {
this(context, cancelable, cancelListener,
resolveDialogTheme(context, 0));
}
protected AlertDialog(Context context, boolean cancelable,
OnCancelListener cancelListener, int theme) {
super(context, resolveDialogTheme(context, theme));
setCancelable(cancelable);
setOnCancelListener(cancelListener);
mAlert = new AlertController(context, this, getWindow());
}
protected AlertDialog(Context context, int theme) {
this(context, false, null, theme);
}
public Button getButton(int whichButton) {
return mAlert.getButton(whichButton);
}
public ListView getListView() {
return mAlert.getListView();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlert.installContent();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mAlert.onKeyDown(keyCode, event)) {
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (mAlert.onKeyUp(keyCode, event)) {
return true;
}
return super.onKeyUp(keyCode, event);
}
#Deprecated
public void setButton(CharSequence text, Message msg) {
setButton(BUTTON_POSITIVE, text, msg);
}
#Deprecated
public void setButton(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_POSITIVE, text, listener);
}
public void setButton(int whichButton, CharSequence text, Message msg) {
mAlert.setButton(whichButton, text, null, msg);
}
public void setButton(int whichButton, CharSequence text,
OnClickListener listener) {
mAlert.setButton(whichButton, text, listener, null);
}
#Deprecated
public void setButton2(CharSequence text, Message msg) {
setButton(BUTTON_NEGATIVE, text, msg);
}
#Deprecated
public void setButton2(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_NEGATIVE, text, listener);
}
#Deprecated
public void setButton3(CharSequence text, Message msg) {
setButton(BUTTON_NEUTRAL, text, msg);
}
#Deprecated
public void setButton3(CharSequence text, final OnClickListener listener) {
setButton(BUTTON_NEUTRAL, text, listener);
}
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public void setIcon(Drawable icon) {
mAlert.setIcon(icon);
}
public void setIcon(int resId) {
mAlert.setIcon(resId);
}
public void setIconAttribute(int attrId) {
TypedValue out = new TypedValue();
getContext().getTheme().resolveAttribute(attrId, out, true);
mAlert.setIcon(out.resourceId);
}
public void setInverseBackgroundForced(boolean forceInverseBackground) {
mAlert.setInverseBackgroundForced(forceInverseBackground);
}
public void setMessage(CharSequence message) {
mAlert.setMessage(message);
}
#Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
public void setView(View view) {
mAlert.setView(view);
}
public void setView(View view, int viewSpacingLeft, int viewSpacingTop,
int viewSpacingRight, int viewSpacingBottom) {
mAlert.setView(view, viewSpacingLeft, viewSpacingTop, viewSpacingRight,
viewSpacingBottom);
}
}

Categories

Resources