Disable pre-checked checkbox alert dialog android java - java

ListView lv = ((AlertDialog) dialog).getListView();
SparseBooleanArray checkedItems = lv.getCheckedItemPositions();
if (checkedItems != null) {
for (int i = 0; i < checkedItems.size(); i++) {
//if (checkedItems.valueAt(i)) {
if (checkedItems.get(i)) {
lv.getChildAt(checkedItems.keyAt(i)).setEnabled(false);
String item = lv.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
Log.i("TAG", item);
}
}
}
I am getting all the pre-checked checkbox on load of alert dialog in android. Now, I want to disable the pre-checked checkbox using :
lv.getChildAt(checkedItems.keyAt(i)).setEnabled(false);
But it is not working any idea how to disable is appreciated.

SparseBooleanArray checkedItems = lv.getCheckedItemPositions();
It means just 'checked item'. Your code access just a value in each check boxes. How about access into listview and operate the access?
I think you should access into listview directly.

AlertDialog.Builder builder = new AlertDialog.Builder(A);
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
AlertDialog dialog = (AlertDialog) dialog;
ListView v = dialog.getListView();
int i = 0;
for (int i = 0; i < items. length; i++) {
v.setItemChecked(i, false); // true if you want to check all
i++;
}
}
});

Maybe for someone it will be useful.
((CheckedTextView)lv.getChildAt(i)).setChecked(isChecked);

Related

Checkbox true/false for ischecked working, But not displaying the ui check mark

I have a list of timezones that gets added to a recycler view. However, my main list in the activity checks properly but when I use the search and the list condenses and I click the checkbox it will not show the checkmark. However, in debug, the value is set to true when clicked and it will still add it into the recycler view properly.
I have tried looking online but there was no solution for this specific problem.
#Override
public void onBindViewHolder(#NonNull final TimezoneViewHolder holder, final int position) {
// Initialize tools
final Timezone_Item currentTimezoneItem = timezoneList.get(position);
int pos = currentTimezoneItem.getId();
final int tzID = --pos;
holder.mChkboxSelect.setText(currentTimezoneItem.getValue());
holder.mUTCCode.setText(currentTimezoneItem.getName());
// This is the solution for... Clicking the checkbox once would select multiple timezones. Not with this.
if(selectedTimezones.get(position)){
holder.mChkboxSelect.setChecked(true);
currentTimezoneItem.setIsSelected(true);
}else{
holder.mChkboxSelect.setChecked(false);
currentTimezoneItem.setIsSelected(false);
}
// Manually activate the clicks in checkbox
holder.mChkboxSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(currentTimezoneItem.getIsSelected()){
currentTimezoneItem.setIsSelected(false);
holder.mChkboxSelect.setChecked(false);
}else {
currentTimezoneItem.setIsSelected(true);
holder.mChkboxSelect.setChecked(true);
}
if(TimezonePickerActivity.isSearching){
selectedTimezones.put(currentTimezoneItem.getId() - 1, currentTimezoneItem.getIsSelected());
}else {
selectedTimezones.put(tzID, currentTimezoneItem.getIsSelected());
}
notifyDataSetChanged();
}
});
}
This is my Search filter...
private Filter SearchFilter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence searchText) {
List<Timezone_Item> filteredList = new ArrayList<>();
if (searchText == null || searchText.length() == 0) {
TimezonePickerActivity.isSearching = false;
filteredList.addAll(timezoneListFull);
} else {
String filterPattern = searchText.toString().toLowerCase().trim();
TimezonePickerActivity.isSearching = true;
for (Timezone_Item item : timezoneListFull) {
if (item.getName().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults filterResults = new FilterResults();
filterResults.values = filteredList;
return filterResults;
}
#Override
protected void publishResults(CharSequence searchText, FilterResults results) {
timezoneList.clear();
timezoneList.addAll((List) results.values);
notifyDataSetChanged();
}
};
This is my code to add the selected timezone into the recycler view
fabAddTimezone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { SparseBooleanArray selectedTimezones = Timezone_RVAdapter.selectedTimezones;
// Filter out false values
for (int i = 0; i < selectedTimezones.size(); i++) {
if(!selectedTimezones.valueAt(i)){
selectedTimezones.removeAt(i);
selectedTimezones.delete(i);
}
}
// Take filtered values and find its index to grab text and UTC code
for (int i = 0; i < selectedTimezones.size(); i++) {
// Get the position(Key) which is actually the Timezone_Item ID
int position = selectedTimezones.keyAt(i);
// Create new clock item to add into list
Clock_Item clockItem = new Clock_Item(
Timezone_RVAdapter.timezoneListFull.get(position).getName(),
Timezone_RVAdapter.timezoneListFull.get(position).getValue()
);
// Add clock to a list
mClockList.add(clockItem);
}
// Save clock list
sharedPrefs.SaveClockList(mClockList);
// Go back to main menu. Clock list should automatically load once activity boots
finish();
}
});
There is a possibility that the below block is always true
if(currentTimezoneItem.getIsSelected()){
currentTimezoneItem.setIsSelected(false);
//Calling the below statement is irrelevant inside onClick of itself
//because when inside here checkbox can never be checked
holder.mChkboxSelect.setChecked(false);
}
remove or comment out every line statement calling .setChecked on mChkboxSelect and allow android handle the state. You can control the state of a checkbox but not inside it's onClick event because clicking on a checkbox automatically changes the state.

Restoring CheckBox state in an ArrayList never sets CheckBoxes as checked

I'm attempting to restore a list of checkboxes's 'ischecked' state however the boxes are never checked for some reason.
I'm sure I'm overlooking something small.
Any suggestions are appreciated.
Source:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_notification_settings_list_new_message);
pref = getApplicationContext().getSharedPreferences("PREFS", 0);
final int selection = pref.getInt("ChatRepeatPosition", 0);
ButterKnife.bind(this);
getSupportActionBar().setTitle("Repeat Notification In");
list = (ListView) findViewById(R.id.simpleListView);
dataAdapter = new ArrayAdapter<String>(this, R.layout.repeat,
R.id.repeat_tv, text);
list.setAdapter(dataAdapter);
list.setChoiceMode(ListView.CHOICE_MODE_NONE);
if (list != null && selection != 0) {
for (int i = 0; i < list.getCount(); i++) {
CheckBox cb = new CheckBox(this);
cb.setId(i);
if (i == selection) {
cb.setChecked(true);
} else {
CheckBox cbb = new CheckBox(this);
cbb.setChecked(false);
}
}
}
Full Source:
https://pastebin.com/tAMTam3X
Edit:
The first 'answer' shown below is not what I'm attempting on accomplish. I fully understand how to restore the state of a single checkbox. I'm having trouble iterating through my list of checkboxes to restore the state of all of them (I am able to iterate through the list in list.setOnItemClickListener because I can get the view - but I'm not sure how to iterate through the list in oncreate)
checkbox list image
The problem is that you're creating new CheckBox objects and not doing anything with them:
for (int i = 0; i < list.getCount(); i++) {
CheckBox cb = new CheckBox(this);
cb.setId(i);
if (i == selection) {
cb.setChecked(true);
} else {
CheckBox cbb = new CheckBox(this);
cbb.setChecked(false);
}
}
This loops through the size of the list, initializes CheckBoxs, sets the checked state on those CheckBoxs and then ... well, that's it. They are in no way associated with the ListView, so how would its state get updated?
What you want to do is use the setItemChecked method, something like this:
final int selection = pref.getInt("ChatRepeatPosition", 0);
list = (ListView) findViewById(R.id.simpleListView);
list.setItemChecked(selection, true);
And you can delete the for loop that literally does nothing.
If you want to read more than one saved selection, then you would need to read from a database or file since preferences are limited to key / value pairs. But the concept would be the same: read the list of selections, iterated through the list, set the item checked on the list view.
Hope that helps!
try this.. in the on create add your checkbox and initialize it.
cb1 = (CheckBox) findViewById(R.id.yourxmlid);
then add a shared pref to check the state of the check box
sharedpreferences = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedpreferences.edit();
boolean checkedFlag1 = sharedpreferences.getBoolean("checkboxstate", false);
cb1.setChecked(checkedFlag1);
then finally in your onCheckListener add a shared pref to check the box
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (cb1.isChecked()) {
editor.putBoolean("checkboxstate", true);
editor.commit();
Log.i("Checkbox ", "Activated");
}else{
editor.putBoolean("checkboxstate", false);
editor.commit();
Log.i("Checkbox: ","Deactivated");
}
}
});

How to get data from many EditTexts when Its added in layout programmatically in android

I'm adding EditText in linear layout and it gives a view like that in image.
I'm getting this view by using this code.
public class SearchRecipe extends AppCompatActivity {
LinearLayout parentLayout;
ImageButton searchRecipe;
private int EDITTEXT_ID = 1;
private List<EditText> editTextList;
EditText editTextItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_recipe);
setActionBar();
init();
searchRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText editTextItem = (EditText) parentLayout.findViewById(EDITTEXT_ID);
for (int i = 0; i < editTextList.size(); i++) {
Log.e("All Values=", editTextList.get(i).getText().toString());
Toast.makeText(SearchRecipe.this, editTextItem.getText().toString() + " ", Toast.LENGTH_SHORT).show();
}
}
});
}
public void init() {
parentLayout = (LinearLayout) findViewById(R.id.parent_layout); //make sure you have set vertical orientation attribute on your xml
searchRecipe = (ImageButton) findViewById(R.id.search_button);
editTextList = new ArrayList<EditText>();
TextView addMoreText = new TextView(this);
addMoreText.setText("Add More Ingredients");
addMoreText.setGravity(Gravity.CENTER);
addMoreText.setPadding(20, 20, 20, 20);
addMoreText.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.add, 0);
addMoreText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editTextItem = new EditText(SearchRecipe.this);
editTextItem.setId(EDITTEXT_ID);
editTextList.add(editTextItem);
EDITTEXT_ID++;
editTextItem.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.cross, 0);
editTextItem.setPadding(20, 20, 20, 20);
editTextItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
parentLayout.removeView(editTextItem);
return true;
}
});
parentLayout.addView(editTextItem, 0);
}
});
parentLayout.addView(addMoreText);
}
Now the only problem I'm facing is that. I'm not getting the text from edittext properly. Let me Explain what I want to do.
Click on Add More TextView will add one more edit text.
After adding all edittexts I will click on Search button.
By clicking search button will get the data from edittexs and save in arraylist. I tried a lot but can't do this properly. will you please help me to do this thing ? I'm stuck in from many days.
if you are createing edit text run time only for this purpose then there is no need of below tow lines
editTextItem.setId(EDITTEXT_ID);
EDITTEXT_ID++;
To retrive data from each edit box follow below things
for (EditText editText : editTextList) {
/* now you can get the value from Edit-text and save in the ArrayList
or you can append it in same string*/
yourArraList.add(editText.getText().toString()));
}
Get the editext from your list editTextList
String data = editTextList.get(index).getText().toString();
Add check for editTextList should not be null or empty.
You can iterate over list using for-each loop
for (EditText editText : editTextList) {
// now you can get the value from Edit-text and save in the ArrayList
yourArraList.add(editText.getText().toString()));
}
you can do like below if view inside fragment.
public static String getText(final Activity activity) {
final StringBuilder stringBuilder=new StringBuilder();
LinearLayout scrollViewlinerLayout = (LinearLayout) activity.findViewById(R.id.linearLayoutForm);
ArrayList<String> msg = new ArrayList<String>();
for (int i = 0; i < scrollViewlinerLayout.getChildCount(); i++)
{
LinearLayout innerLayout = (LinearLayout) scrollViewlinerLayout.getChildAt(i);
EditText editText = (EditText) innerLayout.findViewById(R.id.meeting_dialog_et);
msg.add(editText.getText().toString());
}
for (int j=0;j<msg.size();j++)
{
stringBuilder.append(msg.get(j)).append(";");
}
Toast t = Toast.makeText(activity.getApplicationContext(), stringBuilder.toString(), Toast.LENGTH_SHORT);
t.show();
return stringBuilder.toString();
}
there is another way is make arraylist Edittexes and add each edittext when it added to layout. then you can get like below:
for (int i = 0; i < Edittexes.size(); i++) {
if (Edittexes.get(i) == view)
{
String text=Edittexes.get(i).getText();
}
}

Local variable not visible inside OnClickListener

I'm developing an Android application and I have a problem:
I have this method:
// User has introduced an incorrect password.
private void invalidPassword()
{
// R.id.string value for alert dialog title.
int dialogTitle = 0;
// R.id.string value for alert dialog message.
int dialogMessage = 0;
boolean hasReachedMaxAttempts;
clearWidgets();
numIntents++;
hasReachedMaxAttempts = (numIntents > maxNumIntents);
// Max attempts reached
if (hasReachedMaxAttempts)
{
dialogTitle = R.string.dialog_title_error;
dialogMessage = R.string.dialog_message_max_attempts_reached;
}
else
{
dialogTitle = R.string.dialog_title_error;
dialogMessage = R.string.dialog_message_incorrect_password;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(dialogMessage)
.setTitle(dialogTitle);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// TODO: User clicked OK button
if (hasReachedMaxAttempts)
{
}
else
{
}
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
How can I make visible boolean hasReachedMaxAttempts; inside onClick?
you need that variable to be final;
final boolean hasReachedMaxAttemptsFinal = hasReachedMaxAttempts;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
if (hasReachedMaxAttemptsFinal)
Declare your final boolean hasReachedMaxAttempts; variable at class level and it should get the task done
It is visible, but it needs to be set to final.
final boolean hasReachedMaxAttempts = (numIntents > maxNumIntents);

onItemContextMenu and button created programatically problem

I would like if anybody could help to solve the problem, that I'm trying to fix in my code. I'm really despearte!
I would like to know if it's possible get from the contextmenu, all the information of the button that I created, and use the setText function later.
Ok, first of all I create a tablerow with some buttons (like a soundboard application)
for (int j = 0 ; index > 0 && j < 2 ; j++) {
final CustomToggleButton tagB = new CustomToggleButton(this);
tagB.setId(index);
...
...
registerForContextMenu(tagB);
tagB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
....
}
...
}
}
Secondly, I let every button an "edit" option for changing the text in it:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle("Opciones de la etiqueta");
menu.add(0, v.getId(), 0, "Edit");
}
Finally I use onContextItemSelected for creating an EditText Alert and let the possibility of introduce the new text.
#Override
public boolean onContextItemSelected(final MenuItem item) {
if (item.getTitle() == "Edit") {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText input = new EditText(this);
alert.setView(input);
alert.setTitle("Nombre del tag");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString().trim();
Log.v(null, "nombre del tag nuevo: "+value);
Toast.makeText(getApplicationContext(), value,Toast.LENGTH_SHORT).show();
int button_id = item.getItemId(); // BUTTON ID?
//CustomToggleButton tagB = (CustomToggleButton) findViewById(R.id.button_id);//DOESN'T WORK!!
//CustomToggleButton tagB = (CustomToggleButton) findViewById(button_id); // NEITHER DOESN'T WORK!!
}
});
alert.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
return true;
}
else return super.onContextItemSelected(item);
}
The problem is that I can't use its id from R.java, because I have created the button programatically...
Is there any solution for this problem??
You don't need the ID of the button. You need to reference the Button object you created via code.
Edit: Just define the button object with the scope you require. You probably need class scope. You could use an array or list if you would like. Depending on how many buttons you have, that may be the way to go.

Categories