I'm trying without success to unselect all my checkbox picks
by pressing any button that in my java android program with this code
public void onListItemClick(ListView parent, View v, int position, long id)
{
parent.setItemChecked(position, parent.isItemChecked(position));
}
#Override
protected Dialog onCreateDialog(int id, Bundle args){
switch(id){
case 1:
return new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle("This is a dialog with some simple text...")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"OK clicked!", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
Toast.makeText(getBaseContext(),"Cancel clicked!", Toast.LENGTH_SHORT).show();
}
})
.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
Toast.makeText(getBaseContext(),items[which] + (isChecked ? " checked!":" unchecked!"),Toast.LENGTH_SHORT).show();
}
})
.create();
}
return(null);
}
how to select all and unselect all ?
Well, my best guess is to save a reference for all of them on a list, and go through all of them selecting or unselecting them all. Something like this.
Crete a reference to hold all your checkboxes
List<CheckBox> myCheckBoxes = new ArrayList<CheckBox>();
myCheckBoxes.add(cb1);
myCheckBoxes.add(cb2);
myCheckBoxes.add(cb3);
....
Create a method that will get the value you want to set on the check boxes and call it whenever you want.
:
private checkAll(boolean value) {
for(CheckBox cb : myCheckBoxes) {
cb.setChecked(value);
}
}
Create two buttons:
Button unselectAllButton = (Button) findViewById(R.id.unCheckButton);
Button selectAllButton = (Button) findViewById(R.id.checkButton);
unselectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(false);
}
});
selectAllButton.setOnClickListener(setOnClickListener(new OnClickListener() {
public void onClick(View v) {
checkAll(true);
}
});
Related
Iam creating a dialog with following code, who creates multiple choice check box.. But I don't know how to create their id's to add click event , I m new to android please help me..:
private void showDailog() {
final String[] items = {" Blue", " Red", " Black", " White", " Pink"};
final ArrayList itemsSelected = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select any theme you want : ");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int selectedItemId,
boolean isSelected) {
if (isSelected) {
itemsSelected.add(selectedItemId);
} else if (itemsSelected.contains(selectedItemId)) {
itemsSelected.remove(Integer.valueOf(selectedItemId));
}
}
})
.setPositiveButton("Done!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
//Your logic when OK button is clicked
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id)
}
});
dialog = builder.create();
dialog.show();
}
Instead of Alert Dialog create a simple dialog with your custom layout like this
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog_lauout);
dialog.show();
Button button = (CheckBox) dialog.findViewById(R.id.button);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
I've been struggling with this for a while now, looking for any tips how to proceed. I'm trying to create a fragment that has an add button, that will create a new textview and when clicking the textview , you would have the option to delete it.
Adding textviews works fine. The problem is in the foreach loop that sets up listeners for each textview and adds the option to delete them. It's forcing me to declare the current parameter final, or the deletion won't work. But if I do declare it final, then I can't add any new textviews to the list, so they wont have listeners.
So if anyone could give me some kind of a hint, that would be hugely appreciated.
Here's the list and the adding part.
//Variables
List<TextView> TextViews = new ArrayList<TextView>();
#Override
//Put button functionality here
public void onClick(View v) {
final LinearLayout myLayout = (LinearLayout) view.findViewById(R.id.linearlayout);
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Title");
// Set up the input/
final EditText input = new EditText(getContext());
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
notesIndex = new Integer(notesIndex + 1);
noteText = input.getText().toString();
TextView a = new TextView(view.getContext());
a.setText(noteText);
a.setHeight(150);
a.setGravity(Gravity.CENTER);
myLayout.addView(a);
TextViews.add(a);
noteTexts.add(noteText);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
And here is the foreach loop that sets up listeners for each TextView. They are both called in OnCreateView.
for (final TextView current : TextViews) {
current.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete?");
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myLayout.removeView(current);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
});
}
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
addViewToLayout();
}
});
void addViewToLayout(){
notesIndex = new Integer(notesIndex + 1);
noteText = input.getText().toString();
TextView a = new TextView(view.getContext());
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showAlertToDelete(v)
}
});
a.setText(noteText);
a.setHeight(150);
a.setGravity(Gravity.CENTER);
myLayout.addView(a);
TextViews.add(a);
noteTexts.add(noteText);
}
void showAlertToDelete(View v){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Delete?");
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
myLayout.removeView(v);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
By reading the documentation, I have managed to create a multiple choice dialog box. However, there's one bit that still has me completely stumped. When the user clicks "Okay", how do I return them to the parent Activity?
I"m referring to this particular comment:
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
...
}
How exactly would I 'return them to the component that opened the dialog'?
My dialog call in my activity:
public void chooseTeam(View v) {;
DialogFragment newDialog = MultiChoiceDialog.newInstance(teamNamesArray);
newDialog.show(getFragmentManager(), "Choose_team");
}
and my dialog code:
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] team = getArguments().getStringArray("team");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.choose_team).setMultiChoiceItems(team, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
list.add(team[which]);
} else if (list.contains(team[which])) {
list.remove(team[which]);
}
}
}).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selections = "";
for (String ms : list) {
selections = selections + "\n" + ms;
}
Toast.makeText(getActivity(), "Team Selected: " + selections,
Toast.LENGTH_LONG).show();
AddTaskActivity.chosenTeam = list;
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Toast.makeText(getActivity(), "Cancelled.", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
You can make the ArrayList a class member variable like private ArrayList mSelectedItems;
See example code below
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList mSelectedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSelectedItems = new ArrayList();
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
// Set the dialog title
builder.setTitle(R.string.pick_toppings)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(R.array.toppings, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK, so save the mSelectedItems results somewhere
// or return them to the component that opened the dialog
// in this case the OK button has more or less no function but if want save the check options in database or shared preference, you can put your code here. So it depends on your use case.
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}
}
I have a button inside a popupwindow that when clicked initializes an alertdialog with a list from which the user can choose from. I'm stuck trying to get the string value of the selected item from the list. I'm trying to get the item and then change the description text on the button to reflect the user's selection.
countryButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//String countryResult = countryList.get(which);
//countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});
You have to use ArrayAdapter.getItem() method. And if it isn´t just a copy paste mistake, don´t forget the #Override annotation. But what do You mean with "missing reference error"?
countryButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
final ArrayAdapter<CharSequence> countryAdapter = ArrayAdapter.createFromResource(getApplicationContext(), R.array.countries_array, android.R.layout.simple_spinner_item);
new AlertDialog.Builder(MakeQuestion.this)
.setTitle("Country")
.setAdapter(countryAdapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String countryResult = countryAdapter.getItem(which);//use this getItem() method
countryButton.setText(countryResult);
dialog.dismiss();
}
}).create().show();
}
});
I have a simple application (really!) that displays a list and then displays the details of an item on the list based on the user's choice. I do this using Fragments. The details portion is a Fragment which has an EditText in it. Currently, if the user types in the EditText and clicks on the Save button, an AlertDialog.Builder pops up asking her if she wants to save. If she chooses yes, the text is saved to a database. I want the same thing to happen if the user hits the back button. In my class that extends FragmentActivity, I have:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
super.onKeyDown(keyCode, event);
DetailFrag frag = (DetailFrag) getSupportFragmentManager().findFragmentById(R.id.frag_stitchdetail);
frag.onKeyDown(keyCode, event);
return false;
}
In my class that extends Fragment (the details portion), I have:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER && event.getRepeatCount() == 0
&& Edited) {
return true;
}
else
return false;
}
I'm not sure where to put the code that will call the AlertDialog.Builder. I want to put it in the Fragment class because the code needs to get the rowID of the detail from the list (a class that extends ListFragment). That information isn't available to the FragmentActivity class. For clarification, here's the code I use to operate the Save button. It's called from the onCreateView method of the Fragment class and I want to re-use this code (put it in its own method, probably) when the back button is hit.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detailfragment, container, false);
Typeface danielFont = Typeface.createFromAsset(getActivity().getAssets(),
"danielbk.ttf");
final EditText notes = (EditText)view.findViewById(R.id.stitchnotes);
notes.setTypeface(danielFont);
notes.setTextSize(12);
builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want to save your Notes?");
builder.setCancelable(false);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String Notes = notes.getText().toString();
Uri updateUri = ContentUris.withAppendedId(STITCHES_URI, rowID);
ContentValues values = new ContentValues();
values.put("stitchnotes", Notes);
getActivity().getContentResolver().update(updateUri,values,null,null);
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
//getActivity().finish();
}
});
alert = builder.create();
ImageButton savebutton = (ImageButton)view.findViewById(R.id.savebutton);
savebutton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
alert.show();
}
});
notes.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
Edited = true;
}
});
return view;
}
The rowID that's used when I declare updateURI comes from the ListFragment class like so:
DetailFrag frag = (DetailFrag) getFragmentManager().findFragmentById(R.id.frag_stitchdetail);
if (frag != null && frag.isInLayout()) {
//more code
frag.setRowID(stitchid);
}
setRowID is defined in the Fragment class:
public void setRowID(int row_id)
{
rowID = row_id;
}
and rowID is a private static int in the Fragment class.
Can someone please point me in the right direction?
Two options I can see.
One:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK) {
backPressed = true;
alert.show();
return true; // shows you consumed the event with your implementation
}
// blah, blah, other code
}
Add the following lines to your dialog yes and no OnClickListeners:
if (backPressed){
finish();// - to exit the Activity
}
Alternately, create two separate builders as follows:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// other code
builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Do you want to save your Notes?");
builder.setCancelable(false);
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
saveNotes();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertSave = builder.create();
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
saveNotes();
finish();
}
});
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
finish();
}
});
alertBack = builder.create();
ImageButton savebutton = (ImageButton)view.findViewById(R.id.savebutton);
savebutton.setOnClickListener(new ImageButton.OnClickListener() {
public void onClick(View v) {
alertSave.show();
}
});
// other code
}
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK) {
alertBack.show();
return true; // shows you consumed the event with your implementation
}
// blah, blah, other code
}
private void saveNotes() {
String Notes = notes.getText().toString();
Uri updateUri = ContentUris.withAppendedId(STITCHES_URI, rowID);
ContentValues values = new ContentValues();
values.put("stitchnotes", Notes);
getActivity().getContentResolver().update(updateUri,values,null,null);
}