I have an AlertDialog which it has dynamic items linked to a Cursor from database , it works fine but i wanted to disable user interaction with that because it's an informational dialog , i've disabled my dialog with :
alert.getListView().setEnabled(false);
but the problem is when Items in the list are bigger than the dialog height , because of disabling it's ListView, Scrolling is disabled too and some items doesn't show up, i've tried some links like : Android : How to disable CheckBox in AlertDialog?
with no success. i've also tried :
builder.setMultiChoiceItems(mDBAdapter.instance.getName(SupervisorGuid)
, SyncDBHelper.instance.SentSupervisors(SupervisorGuid),new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if(isChecked==true)
{
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
else
{
((AlertDialog) dialog).getListView().setItemChecked(which, true);
}
}});
AlertDialog alert = builder.create();
Does anybody know a better way to disable the checkboxes without a Custom dialog?
Thanks in Advance.
this may give you some idea...
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
ArrayList<String> arrayList = new ArrayList<String>();
ArrayList<Boolean> selectedList = new ArrayList<Boolean>();
for (int i = 1; i <= 20; i++) {
arrayList.add("" + i);
selectedList.add(i % 2 == 0);
}
builder.setAdapter(new MyAdapter(arrayList, selectedList), null);
builder.show();
}
public static class MyAdapter extends BaseAdapter {
private ArrayList<String> arrayList;
private ArrayList<Boolean> selectedList;
public MyAdapter(ArrayList<String> arrayList,
ArrayList<Boolean> selectedList) {
this.arrayList = arrayList;
this.selectedList = selectedList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return getView(parent.getContext(), position);
}
private RelativeLayout getView(Context context, int position) {
RelativeLayout relativeLayout = new RelativeLayout(context);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
relativeLayout.setLayoutParams(params);
TextView textView = new TextView(context);
textView.setText(arrayList.get(position));
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
layoutParams.leftMargin = 30;
textView.setLayoutParams(layoutParams);
relativeLayout.addView(textView);
CheckBox checkBox = new CheckBox(context);
layoutParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layoutParams.rightMargin = 30;
checkBox.setLayoutParams(layoutParams);
checkBox.setClickable(false);
if (selectedList != null) {
checkBox.setChecked(selectedList.get(position));
}
relativeLayout.addView(checkBox);
return relativeLayout;
}
}
I had the same problem and solved it this way:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
...
builder
.setTitle(...)
.setMultiChoiceItems(cursor, IS_CHECKED, LABEL, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
((AlertDialog)dialog).getListView().setItemChecked(which, /* assign here the original boolean value of the item */);
}
})
...
AlertDialog dialog = builder.create();
dialog.show();
In summary, when you click the item in the list, just set its value back to the original boolean value.
you can define your check box value with boolean array
"checkValues" is our boolean array which defines which check box should tick or which not. check below ex.
builder.setMultiChoiceItems(dialogList, checkedValues)
private fun showDialog() {
val dialogList: Array<String> = days
val checkedValues = BooleanArray(days.size)
checkedValues[viewpager.currentItem] = true
val builder: AlertDialog.Builder = AlertDialog.Builder(activity)
builder.setTitle("You can copy"+dialogList[viewpager.currentItem]+" time slot to:")
builder.setMultiChoiceItems(dialogList, checkedValues)
{ dialog, which, isChecked ->
(dialog as AlertDialog).listView.setItemChecked(yourIndex, true)
}.setPositiveButton("OK") { dialog, id ->
dialog.dismiss()
}.setNegativeButton("Cancel") { dialog, id ->
dialog.dismiss()
}.show()
}
Related
In my listview, when I long press row 1 it should change the amount of a textview in row 1. However I have a problem, when I try to change the amount of the specific row (example: row 1), the 5th row of the listview also changes. Also, when the listview is recycled, the textview returns to its old value. Been trying to solve this for a day already but to no luck.
Any help is appreciated!
public View getView(int i, View convertView, ViewGroup viewGroup) {
View mView = convertView;
String betid = mData.get(i).get("id");
final ViewHolder holder;
if (mView == null) {
Context context = viewGroup.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
mView = inflater.inflate(R.layout.row_layout, null, false);
holder = new ViewHolder();
holder.tx_number = (TextView) mView.findViewById(R.id.tx_number);
holder.tx_amount = (TextView) mView.findViewById(R.id.tx_amount);
holder.checkBox = (CheckBox) mView.findViewById(R.id.checkmark);
holder.tx_status = (TextView) mView.findViewById(R.id.tx_status);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
checked.add((Integer) holder.checkBox.getTag());
holder.tx_amount.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_number.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_status.setBackgroundColor(getResources().getColor(R.color.bluelim));
} else {
holder.tx_amount.setBackgroundColor(Color.WHITE);
holder.tx_number.setBackgroundColor(Color.WHITE);
holder.tx_status.setBackgroundColor(Color.WHITE);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
txAmt.setText(zzx);
holder.tx_status.setText(zzx);
holder.tx_amount.setText(zzx);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
mView.setTag(holder);
holder.checkBox.setTag(i);
} else {
holder = (ViewHolder) mView.getTag();
((ViewHolder) mView.getTag()).checkBox.setTag(i);
}
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("betamount");
String status = mData.get(i).get("status");
holder.tx_amount.setText(amountTarget);
holder.tx_number.setText(betnumber);
holder.tx_status.setText(status);
}
ViewHolder holde2r = (ViewHolder) mView.getTag();
for (int k = 0; k < checked.size(); k++) {
if (checked.get(k) == i) {
holde2r.checkBox.setChecked(true);
} else if (checked.get(k) != i) {
holde2r.checkBox.setChecked(false);
}
}
return mView;
}
private class ViewHolder {
TextView tx_number;
TextView tx_amount;
TextView tx_status;
CheckBox checkBox;
}
}
try this. please add this two methods if not added
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
Add notifyDataSetChange on positive button click listener.
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
txAmt.setText(zzx);
holder.tx_status.setText(zzx);
holder.tx_amount.setText(zzx);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
you should learn the listview lifecycle. however if you want to do that you have to change the item data from the datasource which in this case , its mData. and after updateting the item call notifyItemchanged() on adapter to apply the item in listview. the reason for after recycling you see the old data is that the list gets data from mData and you just updated the View. so instead of geting the viewholder. get item by position in longclick and after you updated the item just call notifyItemChanged(position);
First you missed }); in your code before mView.setTag(holder);, so your code will have compile issues which I think you should have seen.
Second, you should not call listView.setOnItemLongClickListener in getView. Because this will repeat many times depends on how many items visible in your screen.
Finally, you should update the data source, i.e.: mData in your code, with the latest data, and then call adapter.notifyDatasetChanged() to update the UI.
So your code should be something like below:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
// Remove codes below
// txAmt.setText(zzx);
// holder.tx_status.setText(zzx);
// holder.tx_amount.setText(zzx);
mData.get(position).setXXX(zzx); // call the setter of your data model
adapter.notifyDatasetChanged(); // call this will update the listview with the latest data
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
});
public View getView(int i, View convertView, ViewGroup viewGroup) {
View mView = convertView;
String betid = mData.get(i).get("id");
final ViewHolder holder;
if (mView == null) {
Context context = viewGroup.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
mView = inflater.inflate(R.layout.row_layout, null, false);
holder = new ViewHolder();
holder.tx_number = (TextView) mView.findViewById(R.id.tx_number);
holder.tx_amount = (TextView) mView.findViewById(R.id.tx_amount);
holder.checkBox = (CheckBox) mView.findViewById(R.id.checkmark);
holder.tx_status = (TextView) mView.findViewById(R.id.tx_status);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
checked.add((Integer) holder.checkBox.getTag());
holder.tx_amount.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_number.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_status.setBackgroundColor(getResources().getColor(R.color.bluelim));
} else {
holder.tx_amount.setBackgroundColor(Color.WHITE);
holder.tx_number.setBackgroundColor(Color.WHITE);
holder.tx_status.setBackgroundColor(Color.WHITE);
}
}
});
mView.setTag(holder);
holder.checkBox.setTag(i);
} else {
holder = (ViewHolder) mView.getTag();
((ViewHolder) mView.getTag()).checkBox.setTag(i);
}
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("betamount");
String status = mData.get(i).get("status");
holder.tx_amount.setText(amountTarget);
holder.tx_number.setText(betnumber);
holder.tx_status.setText(status);
}
ViewHolder holde2r = (ViewHolder) mView.getTag();
for (int k = 0; k < checked.size(); k++) {
if (checked.get(k) == i) {
holde2r.checkBox.setChecked(true);
} else if (checked.get(k) != i) {
holde2r.checkBox.setChecked(false);
}
}
return mView;
}
private class ViewHolder {
TextView tx_number;
TextView tx_amount;
TextView tx_status;
CheckBox checkBox;
}
}
on my main activity screen, I have a button which takes me to another screen. but when I click that my app crashes and I get an error.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.app.appname/com.app.appname.view}:
java.lang.NullPointerException
The blue underline is at view.java at this line:
ArrayList spinnerArrayList =
bundle.getIntegerArrayList("arraylist");
Here is my full view.java code:
public class view extends AppCompatActivity {
private LinearLayout mLinearLayout;
private ArrayList<SearchableSpinner> mSpinners;
private List<AppCompatButton> mButtons = new ArrayList<>();
private List<CheckBox> mCheckboxes = new ArrayList<>();
private List<TextView> mTextviews = new ArrayList<>();
private List<EditText> mEdittexts = new ArrayList<>();
private List<View> mViews = new ArrayList<>();
private Map<String, String> numberItemValues = new HashMap<>();
List<String> itemList = new ArrayList<>();
private Spinner spinner;
private TextView textview;
private CheckBox checkbox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
GlobalClass globalClass = (GlobalClass) this.getApplicationContext();
textview = findViewById(R.id.textview);
checkbox = findViewById(R.id.checkbox);
ArrayList<String> items = new ArrayList<>();
items.add(String.valueOf(mSpinners)); // add you selected item
globalClass.setItems(items);
mSpinners = new ArrayList<>();
mLinearLayout = findViewById(R.id.my_linearLayout);
findViewById(R.id.my_linearLayout).requestFocus();
Intent gotIntent = getIntent();
Bundle bundle = getIntent().getBundleExtra("extraBundle");
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
//creating a for loop, to create the number of spinners in the spinnerarray list size
for(int i = 0; i < spinnerArrayList.size(); i++) {
final Spinner spinner = makeSpinner();
mLinearLayout.addView(spinner);
final View newView = makeView();
//Add a new view
mLinearLayout.addView(newView);
mViews.add(newView);
final EditText newEdittext = makeEdittext();
mLinearLayout.addView(newEdittext);
mEdittexts.add(newEdittext);
final CheckBox newCheckbox = makeCheckbox();
mLinearLayout.addView(newCheckbox);
//TODO add checkbox to your list
mCheckboxes.add(newCheckbox);
final TextView newTextview = makeTextview();
mLinearLayout.addView(newTextview);
mTextviews.add(newTextview);
newCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// makes the set disappear when checkbox is ticked.
newCheckbox.setVisibility(View.VISIBLE);
spinner.setVisibility(View.VISIBLE);
newView.setVisibility(View.VISIBLE);
newEdittext.setVisibility(View.VISIBLE);
newTextview.setVisibility(View.VISIBLE);
//textview.setVisibility(View.VISIBLE);
newCheckbox.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newCheckbox.setVisibility(View.GONE);
}
});
spinner.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
spinner.setVisibility(View.GONE);
}
});
newView.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newView.setVisibility(View.GONE);
}
});
newEdittext.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newEdittext.setVisibility(View.GONE);
}
});
newTextview.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newTextview.setVisibility(View.GONE);
}
});
}
});
//TODO Add the spinner on item selected listener to get selected items
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String currentItem = itemList.get(position);
String aisleNumber = numberItemValues.get(currentItem);
//TODO you can use the above aisle number to add to your text view
//mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
newTextview.setText(aisleNumber);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// code here
}
});
final int listSize = mViews.size();
//code for deleting the said item.
newView.setOnClickListener(new View.OnClickListener() {
//start
#Override
public void onClick(View view) {
//when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.
final View.OnClickListener context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(view.this);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
if (listSize > 0) {
mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
mSpinners.get(listSize - 1).setVisibility(View.GONE);
mViews.get(listSize - 1).setVisibility(View.GONE);
mTextviews.get(listSize - 1).setVisibility(View.GONE);
mEdittexts.get(listSize - 1).setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
//setting spinner selection values
int positionOfSpinner = spinnerArrayList.get(i);
spinner.setSelection(positionOfSpinner);
}
//code for the add button to add more items
FloatingActionButton floatingActionButton =
(FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();
spinner = findViewById(R.id.spinner);
mLinearLayout.setVisibility(View.VISIBLE);
// Handle ze click.
final Spinner spinner = makeSpinner();
mLinearLayout.addView(spinner);
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) spinner.getLayoutParams();
layoutParams.setMargins(5, 100, 10, 0); //top 70
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
layoutParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80
layoutParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240
spinner.setLayoutParams(layoutParams);
final View newView = makeView();
//Add a new view
mLinearLayout.addView(newView);
mViews.add(newView);
final EditText newEdittext = makeEdittext();
mLinearLayout.addView(newEdittext);
mEdittexts.add(newEdittext);
final int listSize = mViews.size();
//code for deleting the said item.
//code for deleting the said item.
newView.setOnClickListener(new View.OnClickListener() {
//start
#Override
public void onClick(View view) {
//when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.
final View.OnClickListener context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(view.this);
// set title
alertDialogBuilder.setTitle("Delete Item");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure you want to delete this item?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
//final int listSize = mViews.size();
if (listSize > 0) {
mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
mSpinners.get(listSize - 1).setVisibility(View.GONE);
mViews.get(listSize - 1).setVisibility(View.GONE);
mTextviews.get(listSize - 1).setVisibility(View.GONE);
mEdittexts.get(listSize - 1).setVisibility(View.GONE);
Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
//Add a new checkbox
final CheckBox newCheckbox = makeCheckbox();
mLinearLayout.addView(newCheckbox);
//TODO add checkbox to your list
mCheckboxes.add(newCheckbox);
newCheckbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// makes the set disappear when checkbox is ticked.
newCheckbox.setVisibility(View.VISIBLE);
spinner.setVisibility(View.VISIBLE);
newView.setVisibility(View.VISIBLE);
newEdittext.setVisibility(View.VISIBLE);
//textview.setVisibility(View.VISIBLE);
newCheckbox.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newCheckbox.setVisibility(View.GONE);
}
});
spinner.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
spinner.setVisibility(View.GONE);
}
});
newView.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newView.setVisibility(View.GONE);
}
});
newEdittext.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
newEdittext.setVisibility(View.GONE);
}
});
/* textview.animate().alpha(0.0f).setDuration(1000).setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
textview.setVisibility(View.GONE);
}
});*/
}
});
final TextView newTextview = makeTextview();
mLinearLayout.addView(newTextview);
mTextviews.add(newTextview);
//TODO Add the spinner on item selected listener to get selected items
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String currentItem = itemList.get(position);
String aisleNumber = numberItemValues.get(currentItem);
//TODO you can use the above aisle number to add to your text view
//mTextviews.get(mTextviews.size() -1).setText(aisleNumber);
newTextview.setText(aisleNumber);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// code here
}
});
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.create_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent startSettingsActivity = new Intent(this, settings.class);
startActivity(startSettingsActivity);
//start the settings activity here.
return true;
}
/* else if (id == R.id.action_delete) {
for(int j=0; j<mCheckboxes.size(); j++){
mCheckboxes.get(j).setVisibility(View.GONE);
}
for(int j=0; j<mSpinners.size(); j++){
mSpinners.get(j).setVisibility(View.GONE);
}
for(int j=0; j<mViews.size(); j++){
mViews.get(j).setVisibility(View.GONE);
}
for(int j=0; j<mTextviews.size(); j++){
mTextviews.get(j).setVisibility(View.GONE);
}
for(int j=0; j<mEdittexts.size(); j++){
mEdittexts.get(j).setVisibility(View.GONE);
}
Toast.makeText(getBaseContext(), "List removed.", Toast.LENGTH_SHORT).show();
return true;
}*/
else if (id ==R.id.action_help) {
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Help");
builder.setMessage("To use this app, first go to Create your Shopping List.\n" +
"Here, you can add items to your list. Once you have added all items, you can click the menu at the top right corner (or if it doesnt appear press your menu button beside your home button on your device, then click View your List.\n" +
"This will take you to the screen where you can view you shopping list with the items in aisle order to make your shop much easier.\n" +
"You can still add items at this point. Press the white background of each item to delete the item if you wish.");
// add a button
builder.setPositiveButton("OK", null);
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
//use a relative layout and specify which ones are to layout_toRightOf and layout_below
//DUPLICATING ITEMS WHEN FAB IS PRESSED//
private CheckBox makeCheckbox() {
//Create new Checkbox
CheckBox checkbox = new CheckBox(this);
// Setup layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
//setup relative layout for the positioning of the objects
Resources resources = getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams((int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)), (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)));
relativeParams.addRule(RelativeLayout.RIGHT_OF, R.id.textview);
checkbox.setLayoutParams(relativeParams);
// RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(relativeParams.addRule(RelativeLayout.RIGHT_OF, R.id.textview));
checkbox.setLayoutParams(layoutParams);
return checkbox;
}
private TextView makeTextview() {
//create new textview
TextView textview = new TextView(this);
//setup layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
textview.setLayoutParams(layoutParams);
textview.setTextSize(30);
return textview;
}
private EditText makeEdittext() {
//create new edittext
EditText edittext = new EditText(this);
//setup layout
final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(50, 50); // Width , height
edittext.setLayoutParams(lparams);
edittext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
edittext.setHint("qty");
return edittext;
}
private View makeView() {
//create new View
View view = new View(this);
view.setBackgroundColor(Color.parseColor("#ffffff"));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100);
new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, 50);
//LinearLayout.LayoutParams.MATCH_PARENT,
// LinearLayout.LayoutParams.WRAP_CONTENT);
view.setClickable(true);
view.setLayoutParams(layoutParams);
//setup layout
return view;
}
private Spinner makeSpinner() {
//opens csv
InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
CSVFile csvFile = new CSVFile(inputStream);
//TODO I made this variable global, declared it at the very top of this file
itemList = csvFile.read();
//Create new spinner
// SearchableSpinner spinner = (SearchableSpinner) new Spinner(this, Spinner.MODE_DROPDOWN);
SearchableSpinner spinner = new SearchableSpinner(this);
// Setup layout
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
spinner.setLayoutParams(layoutParams);
MyListAdapter adapter = new MyListAdapter(this, R.layout.listrow, R.id.txtid, itemList);
spinner.setAdapter(adapter);
//Add it to your list of spinners so you can retrieve their data when you click the getSpinner button
mSpinners.add(spinner);
return spinner;
}
private class CSVFile {
InputStream inputStream;
public CSVFile(InputStream inputStream) {
this.inputStream = inputStream;
}
public List<String> read() {
List<String> resultList = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while ((line = reader.readLine()) != null) {
String[] row = line.split(",");
//TODO I edited this part so that you'd add the values in our new hash map variable
numberItemValues.put(row[1], row[0]);
resultList.add(row[1]);
}
} catch (IOException e) {
Log.e("Main", e.getMessage());
} finally {
try {
inputStream.close();
} catch (IOException e) {
Log.e("Main", e.getMessage());
}
}
return resultList;
}
}}
the create.java intent part
//takes the size of the list of spinners, for reference
ArrayList<Integer> spinnerList = new ArrayList<>();
for(int i = 0; i < mSpinners.size(); i++) {
spinnerList.add(mSpinners.get(i).getSelectedItemPosition());
}
Bundle newBundle = new Bundle();
newBundle.putIntegerArrayList("arraylist", spinnerList);
Intent newIntent = new Intent(create.this, viewscreen.class);
newIntent.putExtra("extraBundle", newBundle);
Can you use put arraylist value like
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("arraylist", arraylist);
And get arraylist value use like below code
Bundle extras = getIntent().getExtras();
extras.getParcelableArrayList("arraylist");
Check codes in main activity button click method, ensure put bundle and data correctly.
and in view activity, suggest writing like this:
Bundle bundle = getIntent().getBundleExtra("extraBundle");
if (bundle!=null) {
if(bundle.containsKey("arraylist") {
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
//do something
}
} else {
//log error info
}
Intent gotIntent = getIntent();
Bundle bundle = getIntent().getBundleExtra("extraBundle");
please print bundle. because the bundle is null then an exception is created
for example:-
send data:-
String[] _string=new String[2];
_string[0]="MONDAY";
_string[1]="TUESDAY";
Intent _intent = new Intent(this, second.class);
Bundle bundle = new Bundle();
_intent .putExtra("strings", myStrings);
_intent .putExtras(bundle);
startActivity(_intent );
receive data:-
Intent i = getIntent();
Bundle extras=i.getExtras();
if(extras != null) //this line is necessary for getting any value
{
String[] _Values = i.getStringArrayExtra("strings");
Toast.makeText(this, "value="+_Values [0]+""+_Values [1], Toast.LENGTH_SHORT).show();
}
Try checking for null value. Maybe the intent is null or the bundle you passed into it is null
Intent gotIntent = getIntent();
if ((gotIntent != null) && (gotIntent.getBundleExtra("extraBundle") != null)) {
Bundle bundle = gotIntent.getBundleExtra("extraBundle");
if(bundle.containsKey("arraylist") {
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
}
}
Try getting the bundle as shown below:-
Intent gotIntent = getIntent();
Bundle bundle = gotIntent.getExtras();
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
The methodgetBundleExtra("String") gets the bundle named String. While getExtras() gets a bundle with all of the items placed into the array.Place your bundle with putExtra(Bundle bundle, String tag) , so that the getBundleExtra(String tag) will return that value.
To check for null ,
if(gotIntent != null && gotIntent.hasExtra("bundleExtras")){
Bundle bundle = gotIntent.getExtras();
ArrayList<Integer> spinnerArrayList = bundle.getIntegerArrayList("arraylist");
}
Make sure you have initialise your activity in your manifest
and use directly like this
ArrayList<Integer> list = getIntent.getIntegerArrayListExtra("")
In my android app, I need to generate one Alertdialog with a list of Company name. For example Company 1, Company 2, Company 3. Now if the user cllick company 1, he will get second alertdialog which will show some actions. Like Phone Call, Email, etc. Now I have implemented this two alertdialog in my code. But what I want to do, that for each company there should be different Phone number and email adress. So Far I have tried with same number with all the company. But in real in real if user click company 1, he will get the second alert list of action with phone call, email. if he clicks phone option he will see the phone number company 1, if he clicks company 2, he will get alertoption with phone number of company 2. But I am very new in developing area. I know there is something with Mapping topic, by which I can do it easily but I am not getting actually how to proceed with it. My code is like this
public List<CompanyDetail> setCompanydata(){
int n = 3;
private List<CompanyDetail> companyDetailList = new ArrayList<CompanyDetail>(); //modifier private is not allowed here
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>(); //modifier private is not allowed here
for(int i=0;i<n;i++){
private CompanyDetail comD= new CompanyDetail(); //modifier private is not allowed here
comD.setcompanyPhoneNo(companyPhoneno); //cannot resolve problem companyPhone
comD.setcompanyEmail(compnayEmailId);
companyDetailList.add(comD);
companyContactDetail.add(companyname, companyDetailList);//cannot resolve method 'add(?,java util list..
}
return companyContactDetail; //incompatible type
}
private List<CompanyDetail> companyDetailList;
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>();
companyContactDetail = setCompanydata(); //unknown class company contact deatil
private void showFirstDialogwithList() {
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
builder.setCancelable(true);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("Contact");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.company_name);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this.getActivity(), R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(arrayAdapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
showSecondDialogwithList();
}
if (itemPosition == 1) {
alert.dismiss();
showSecondDialogwithList();
}
if (itemPosition == 2) {
alert.dismiss();
showSecondDialogwithList();
}
}
});
}
private void showSecondDialogwithList() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("+1234667");
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if(isPermissionGranted()){
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
My string arrays are
<string-array name="company_name">
<item>company 1</item>
<item>Company 2</item>
<item>Company 3</item>
</string-array>
<!-- AlertDialog way of Contact array -->
<string-array name="contact_way">
<item>Phone Call</item>
<item>Email</item>
</string-array>
<String-array name="phone">
<item>123456</item>
<item>125658</item>
<item>123451</item>
</String-array>
<String-array name="email">
<item>email1</item>
<item>email2</item>
<item>email2</item>
</String-array>
you can pass the position for the item and test it at your function or you can pass it directly :
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alert.dismiss();
showSecondDialogwithList(position);
}
private void showSecondDialogwithList(int position) {
String phoneNumber;
switch (position) {
case 1:
phoneNumber = "123";
break;
case 2:
phoneNumber = "456";
break;
case 3:
phoneNumber = "789"
}
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("+1234667");
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if (isPermissionGranted()) {
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
To go deep in to logic behind that kind of scenario best way to use *HashMap*.
according to your scenario. i change in your code check it out:
public class CompanyDetail{
String companyPhoneNo;
String companyEmail;
public void setcompanyPhoneNo(String phoneNo){
this.companyPhoneNo = phoneNo;
}
public void setcompanyEmail(String Email){
this.companyEmail = Email;
}
public String getcompanyPhoneNo(){
return companyPhoneNo;
}
public String getcompanyEmail(){
return companyEmail;
}
}
public HashMap<String, List<CompanyDetail>> setCompanydata(){
int n = 3;
private List<CompanyDetail> companyDetailList = new ArrayList<CompanyDetail>();
private HashMap<String, List<CompanyDetail>> companyContactDetail = new HashMap<String, List<CompanyDetail>>();
for(int i=0;i<n;i++){
CompanyDetail comD= new CompanyDetail();
comD.setcompanyPhoneNo(companyPhoneno);
comD.setcompanyEmail(compnayEmailId);
companyDetailList.add(comD);
companyContactDetail.add(companyname, companyDetailList);
}
return companyContactDetail;
}
private List<CompanyDetail> companyDetailList;
private HashMap<String, List<CompanyDetail>> companyContactDetail;
companyContactDetail = setCompanydata();
private void showFirstDialogwithList() {
//Create a new builder and get the layout.
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
builder.setCancelable(true);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("Contact");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.company_name);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this.getActivity(), R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(arrayAdapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
}
if (itemPosition == 1) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
showSecondDialogwithList();
}
if (itemPosition == 2) {
alert.dismiss();
companyDetailList1 = companyContactDetail.get(companyNameatPosition);
showSecondDialogwithList(Companyname,companyDetailList1 );
showSecondDialogwithList();
}
}
});
}
private void showSecondDialogwithList( String companyName, List<CompanyDetail> companyDetail) {
CompanyDetail obj = companyDetail.get(0);
private String companyPhone = obj.getcompanyPhoneNo();
private String companyEmail = obj.getcompanyEmail();
final AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity(), R.style.DialogStyle);
LayoutInflater inflater = this.getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.first_alertlist_contact, null);
builder.setView(dialogView);
setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle);
//Show the dislog
final AlertDialog alert = builder.show();
//Get the TextView, ListView, Button from the layout.
TextView alertTitle = (TextView) dialogView.findViewById(R.id.title);
Button alertButton = (Button) dialogView.findViewById(R.id.cancel_button);
final ListView alertListView = (ListView) dialogView.findViewById(listView1);
alertTitle.setText("What do you want to do");
// Defined Array values to show in ListView
String[] values = getResources().getStringArray(R.array.contact_way);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this.getActivity(),
R.layout.first_alertlist_textstyle, android.R.id.text1, values);
alertListView.setAdapter(adapter);
alertButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alert.dismiss();
}
});
alertListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
if (itemPosition == 0) {
alert.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(companyPhone);
builder.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// close the dialog, go to login page
if(isPermissionGranted()){
call_action();
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if (itemPosition == 1) {
alert.dismiss();
......;
}
if (itemPosition == 2) {
dismiss();
showEmail();
}
if (itemPosition == 3) {
dismiss();
}
}
});
}
It's not a good practice to display two dialogs one by one. Of course you can implement it, like described above, but it will be much better to display separated activity(fragment) with the list(ListView, RecyclerView) of companies and click on each item will show the dialog with needed params. It will look better from design side and users experience.
I am using the following method do set the mapType of a GoogleMap object named mMap.
private void setMapType() {
final CharSequence[] MAP_TYPE_ITEMS =
{"Road", "Satellite", "Hybrid"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Set map type");
int checkItem = 0;
builder.setSingleChoiceItems(
MAP_TYPE_ITEMS,
checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
break;
case 1:
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
break;
case 3:
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
break;
}
dialog.dismiss();
}
}
);
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.show();
}
What I am trying to do is disable one of the choices, let's say the 1st one (Road).
How could I do that?
P.S.1 I read this AlertDialog with single choice list - I need some items nonclickable but I don't understand how could I make it work in my case.
P.S.2 I tried, this solution too: Android: AlertDialog - how to disable certain choices that are not available Nothing happens. All options are enabled.
It is possible to do this in a standard AlertDialog, but using a custom list adapter. Perhaps the reason the first link you posted did not work for you is because it is important that the list items are updated prior to the dialog being populated.
Creating your dialog:
final CharSequence[] MAP_TYPE_ITEMS =
{"Road", "Satellite", "Hybrid"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Set map type");
int checkItem = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
//specify index 1 is disabled, 0 and 2 will be enabled as normal
list.add(Integer.valueOf(1));
final MyCustomAdapter adapter = new MyCustomAdapter(MAP_TYPE_ITEMS, list);
builder.setAdapter(adapter, null );
builder.setSingleChoiceItems(
MAP_TYPE_ITEMS,
checkItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
Toast.makeText(InitialActivity.this, "Item 0 clicked ", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(InitialActivity.this, "Item 1 clicked ", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(InitialActivity.this, "Item 2 clicked ", Toast.LENGTH_SHORT).show();
break;
}
if( adapter.getItemViewType(item) == 0 ){
dialog.dismiss();
}
}
}
);
AlertDialog fMapTypeDialog = builder.create();
fMapTypeDialog.show();
The custom adapter:
private class MyCustomAdapter extends BaseAdapter {
private ArrayList<String> mData = new ArrayList<String>();
private ArrayList<Integer> mDisabled = new ArrayList<Integer>();
private LayoutInflater mInflater;
public MyCustomAdapter(CharSequence[] items,
ArrayList<Integer> disabledItems) {
mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mDisabled = disabledItems;
for( int i = 0; i< items.length; ++i ){
addItem( items[i].toString());
}
}
public void addItem(final String item) {
mData.add(item);
notifyDataSetChanged();
}
#Override
public int getItemViewType(int position) {
if( mDisabled.contains(position))
return 1; //disabled
return 0; //enabled as normal
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int type = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch(type) {
case 1:
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, null);
holder.textView = (TextView)convertView.findViewById(android.R.id.text1);
convertView.setEnabled(false);
convertView.setClickable(false);
break;
case 0:
convertView = mInflater.inflate(android.R.layout.simple_list_item_1, null);
holder.textView = (TextView)convertView.findViewById(android.R.id.text1);
break;
}
convertView.setTag(holder);
} else {
holder = (ViewHolder)convertView.getTag();
}
holder.textView.setText(mData.get(position));
return convertView;
}
}
Basically, you cann't do it, with simple AlertDialog and Builder. What you trying to do, it's exchange your Views during some interaction, but that items doesn't have such behavior.
But it isn't problem to do it with Custom Dialog. Just for Example...
// create a Dialog component
final Dialog dialog = new Dialog(context);
//Tell the Dialog to use the dialog.xml as it's layout description
// With your own Layouts and CheckBoxs
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Android Custom Dialog Box");
TextView headerTextView = (TextView) dialog.findViewById(R.id.txt);
headerTextView .setText("This is an Android custom Dialog Box Example! Enjoy!");
Button dialogButton1 = (Button) dialog.findViewById(R.id.dialogButton1);
dialogButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialogButton1.setEnabled(false);
dialog.dismiss();
}
});
// And so on, with other buttons
dialog.show();
I answered a pretty similar question here. Basically you can set a listener when a view is added in a given ListView and disable it.
I'm in an Android project.
I want to show a AlertDialog on which the user can pick one item (about 100 items, it's dynamic). I want to add the possibility of searching also.
My real problem is that it seems I can't change the items once the Dialog is created.
The creation code:
// The List with the beaches with radio buttons, single choice!
public void showBeachesDialog(final Activity context, boolean isFromZonas)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
searchAdapter = new SearchDialogAdapater(orderedBeaches, orderedBeachesIds, context);
builder.setSingleChoiceItems(searchAdapter, -1, new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
index = which;
if (!((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).isEnabled())
((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
});
DialogOkOnClickListener listener = new DialogOkOnClickListener(context, isFromZonas);
builder.setPositiveButton(R.string.searchOK, listener);
builder.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// User cancelled the dialog: nothing happens
}
});
builder.setIcon(context.getResources().getDrawable(R.drawable.icon_beach));
builder.setTitle(StaticUtils.DIALOG_TITLE);
View dialogView = context.getLayoutInflater().inflate(R.layout.dialog_beaches, null);
SearchView searchView = (SearchView)dialogView.findViewById(R.id.search_beach);
searchView.setOnQueryTextListener(new SearchQueryListener(searchAdapter));
builder.setView(dialogView);
AlertDialog dialog = builder.create();
dialog.show();
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
}
So, now I have the dialog with all the elements I want (the SearchDialogAdapater is fine).
The DialogOnClickListener is also working.
The search view is appearing on the dialog, and my SearchQueryListener is working perfectly, so I won't post here the code, but in Debug I can see that if I type "d" the elements without the "d" are filtered out.
Now I would like to not throw away all the code and find a way to change the items of the dialog without showing a new one...
Sorry for long question and if there is a obvious way I am missing...
Thank you all.
I solved this using a class that implements 4 interfaces so it can handles everything that I want.
The code is now like this, hope it's useful to someone who want to make its own Dialog with personalized search.
public void showBeachesDialog(final Activity context, boolean isFromZonas)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
searchAdapter = new SearchDialogAdapater
(orderedBeaches, orderedBeachesIds, context, isFromZonas);
builder.setSingleChoiceItems(searchAdapter, -1, null);
builder.setPositiveButton(R.string.searchOK, searchAdapter);
builder.setNegativeButton(R.string.cancelar, null);
builder.setIcon(context.getResources().getDrawable(R.drawable.icon_beach));
builder.setTitle(StaticUtils.DIALOG_TITLE);
View dialogView = context.getLayoutInflater().inflate
(R.layout.dialog_beaches, null);
SearchView searchView = SearchView)dialogView.findViewById
(R.id.search_beach);
searchView.setOnQueryTextListener(searchAdapter);
builder.setView(dialogView);
AlertDialog dialog = builder.create();
dialog.show();
dialog.getListView().setOnItemClickListener(searchAdapter);
searchAdapter.setDialog(dialog);
dialog.getButton(Dialog.BUTTON_POSITIVE).setEnabled(false);
}
The orderedBeaches and orderedBeachesIds are String[] and int[], my data to display.
Below is my adapter which uses a stack to handle the items available at any moment of the searching:
public class SearchDialogAdapater implements ListAdapter, OnQueryTextListener,
OnItemClickListener, OnClickListener {
protected Stack<String[]> stackBeaches;
protected Stack<int[]> stackBeachesIds;
protected Activity context;
protected TreeMap<String, Integer> orderedBeaches;
protected ListView listView;
protected String lastFilter = "";
public SearchDialogAdapater(String[] bs, int[] bIds, Activity cont) {
this.stackBeaches = new Stack<String[]>();
this.stackBeachesIds = new Stack<int[]>();
this.stackBeaches.push(bs);
this.stackBeachesIds.push(bIds);
this.context = cont;
}
#Override
public boolean onQueryTextChange(String newText) {
filter(newText);
this.listView.setAdapter(this);
return true;
}
public void filter(String search) {
// no longer valid the previous selected, must clean selections
selectedPosition = -1;
lastView = null;
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
// hitted "backspace"
if (search.length() < lastFilter.length()) {
if (stackBeaches.size() > 1) {
stackBeaches.pop();
stackBeachesIds.pop();
}
lastFilter = search;
return;
}
// filter
ArrayList<String> filtBs = new ArrayList<String>();
ArrayList<Integer> filtBsIds = new ArrayList<Integer>();
for (int i = 0; i < stackBeaches.peek().length; i++) {
String beach = new String(stackBeaches.peek()[i]);
if (Pattern
.compile(Pattern.quote(search), Pattern.CASE_INSENSITIVE)
.matcher(beach).find()) {
filtBs.add(beach);
filtBsIds.add(stackBeachesIds.peek()[i]);
}
}
String[] beaches = new String[filtBs.size()];
int[] ids = new int[filtBsIds.size()];
int size = filtBs.size();
for (int i = 0; i < size; i++) {
ids[i] = filtBsIds.remove(0);// head
beaches[i] = filtBs.remove(0);
}
stackBeachesIds.push(ids);
stackBeaches.push(beaches);
lastFilter = search;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
String beach = stackBeaches.peek()[position];
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.dialog_item, null);
TextView txtBeach = (TextView) convertView
.findViewById(R.id.dialBeach);
txtBeach.setText(beach);
}
if (position == selectedPosition)// the same color below
convertView.setBackgroundColor(Color.argb(128, 0, 64, 192));
return convertView;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return stackBeachesIds.peek()[position];
}
#Override
public int getCount() {
return stackBeaches.peek().length;
}
#Override
public boolean isEmpty() {
return stackBeaches.peek().length == 0;
}
private View lastView;
private int selectedPosition = -1;
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long arg3) {
// some color...
view.setBackgroundColor(Color.argb(128, 133, 181, 255));
selectedPosition = position;
if (lastView != null)
lastView.setBackground(null);
lastView = view;
((SurfApplication) context.getApplication()).setBeachId(stackBeachesIds
.peek()[position]);
if (!dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled())
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
}
protected AlertDialog dialog;
public void setDialog(AlertDialog dial) {
this.dialog = dial;
this.listView = dialog.getListView();
}
#Override
public void onClick(DialogInterface dialog, int which) {
((ProgressBar) context.findViewById(R.id.pBar))
.setVisibility(ProgressBar.VISIBLE);
int beachId = stackBeachesIds.peek()[selectedPosition];
String beach = stackBeaches.peek()[selectedPosition];
// do something... Here I am creating a new Intent and starting
// the new activity within my context
}
}
Same methods are not here because they return null or do nothing at all.
Sorry for long post, but I need to answer this properly.
Thank you all and I hope someone find this useful.
Your adapter needs to implement Filterable or extend from an adapter class that does. Adapters that already implement this interface, like ArrayAdapter, should do the filtering automatically for you.
Just call Adapter.getFilter().filter(...); with the value from the search view.