I have searched for the answer to this question for a couple of days with no result. When using onClick on a TextView I get the desired result of selecting the word clicked by using:
textView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View arg0) {
Spannable span = (Spannable)textView.getText();
Layout layout = textView.getLayout();
Toast.makeText(arg0.getContext(), "Selection: " + Selection.getSelectionStart(textView.getText().toString()) + Selection.getSelectionEnd(textView.getText().toString()), Toast.LENGTH_SHORT).show();
// returns -1, -1
Toast.makeText(arg0.getContext(), "Selection: " + textView.getSelectionStart() + textView.getSelectionEnd(), Toast.LENGTH_SHORT).show();
//returns -1, -1
Selection.moveToLeftEdge(span, layout);
Selection.extendToRightEdge(span, layout);
final int start = textView.getSelectionStart();
final int end = textView.getSelectionEnd();
String string = textView.getText().toString().substring(start, end);
AlertDialog.Builder builder = new AlertDialog.Builder(arg0.getContext());
builder.setTitle("Delete: " + string)
.setMessage("Are you sure? This operation can't be undone!")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteItem(start, end);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
})
.show();
return true;
}
});
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Spannable span = (Spannable)textView.getText();
Layout layout = textView.getLayout();
Selection.moveToLeftEdge(span, layout);
Selection.extendToRightEdge(span, layout);
writeStrikes(textView.getSelectionStart(), textView.getSelectionEnd());
}
});
When I try using the same code for an onLongClick the selection is -1, -1. If I return false from onLongClick the next selection is where the last should have been. So, the cursor is set when the user releases the long click, after the onLongClick has been called. How do I set the cursor to the position of the long click just before the onLongClick() is called?
Related
I am coding to make a application to manage account and password, everything
is good, only Button Edit has problem. I click it one time, it works normaly, when i click it in second time, it crash. Can you help me?
This is logcat
private ListView listview_account;
private Button add_new;
private EditText newtype, oldtype;
private EditText newusername, oldusername;
private EditText newpassword, oldpassword;
private List<Account> list_accounts;
private String[] list_type;
private MyDatabaseHelper helper = new MyDatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
listview_account = (ListView)findViewById(R.id.list_account);
add_new = (Button)findViewById(R.id.ADD);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView_addnew = inflater.inflate(R.layout.dialog_addnew, null);
final View dialogView_change = inflater.inflate(R.layout.dialog_change, null);
newtype = (EditText)dialogView_addnew.findViewById(R.id.type);
newusername = (EditText)dialogView_addnew.findViewById(R.id.username);
newpassword = (EditText)dialogView_addnew.findViewById(R.id.password);
oldtype = (EditText)dialogView_change.findViewById(R.id.type_old);
oldusername = (EditText)dialogView_change.findViewById(R.id.username_old);
oldpassword = (EditText)dialogView_change.findViewById(R.id.password_old);
update_show();
final AlertDialog.Builder builder_show = new AlertDialog.Builder(this);
final AlertDialog.Builder builder_add = new AlertDialog.Builder(this);
final AlertDialog.Builder builder_delete = new AlertDialog.Builder(this);
final AlertDialog.Builder builder_change = new AlertDialog.Builder(this);
builder_add.setView(dialogView_addnew);
builder_change.setView(dialogView_change);
builder_delete.setTitle("Delete Account");
builder_delete.setIcon(android.R.drawable.ic_delete);
builder_delete.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_change.setTitle("Edit");
builder_change.setIcon(android.R.drawable.ic_input_get);
builder_change.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder_add.setTitle("Add new account");
builder_add.setIcon(android.R.drawable.ic_input_add);
builder_add.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
add_new_account();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), ex.toString(), Toast.LENGTH_LONG).show();
}
}
}
);
builder_add.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
newtype.setText("");
newusername.setText("");
newpassword.setText("");
newtype.requestFocus();
}
}
);
final AlertDialog alert_add_new = builder_add.create();
add_new.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
alert_add_new.show();
}
}
);
listview_account.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v,final int pos, long id) {
builder_show.setTitle(list_type[pos]);
builder_show.setIcon(android.R.drawable.ic_dialog_info);
builder_show.setMessage("Username: " + list_accounts.get(pos).getUSERNAME()
+ "\nPassword: " + list_accounts.get(pos).getPASSWORD());
builder_show.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
builder_delete.setMessage("Do you want to remove " + list_type[pos]+ "?\nUsername: " + list_accounts.get(pos).getUSERNAME() + "\nPassword: " + list_accounts.get(pos).getPASSWORD());
builder_delete.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
helper.DeleteAcc(list_type[pos]);
Toast.makeText(getApplicationContext(), "Success.", Toast.LENGTH_SHORT).show();
update_show();
}
});
final AlertDialog dialog_delete = builder_delete.create();
dialog_delete.show();
}
}
);
builder_show.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
oldtype.setText(list_type[pos]);
oldusername.setText(list_accounts.get(pos).getUSERNAME());
oldpassword.setText(list_accounts.get(pos).getPASSWORD());
builder_change.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
helper.DeleteAcc(list_type[pos]);
change();
}
});
AlertDialog alert_change = builder_change.create();
alert_change.show();
}
}
);
AlertDialog alert1_show = builder_show.create();
alert1_show.show();
}
});
}
private void add_new_account()
{
String new_type = newtype.getText().toString();
String new_username = newusername.getText().toString();
String new_password = newpassword.getText().toString();
Account new_acc = new Account(new_type, new_username, new_password);
helper.AddAccount(new_acc);
update_show();
newtype.setText("");
newusername.setText("");
newpassword.setText("");
newtype.requestFocus();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
private void change()
{
String old_type = oldtype.getText().toString();
String old_username = oldusername.getText().toString();
String old_password = oldpassword.getText().toString();
Account new_acc = new Account(old_type, old_username, old_password);
helper.AddAccount(new_acc);
update_show();
Toast.makeText(getApplicationContext(), "Đã lưu.", Toast.LENGTH_SHORT).show();
}
private void update_show()
{
list_accounts = helper.getListAccount();
list_type = new String[list_accounts.size()];
int i = 0;
for (Account acc: list_accounts) { list_type[i++] = acc.TYPE; }
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, list_type);
listview_account.setAdapter(adapter);
}
As for me, the problem is that you create your builder_show dialog inside your ItemClickListener.
listview_account.setOnItemClickListener(new AdapterView.OnItemClickListener()
Actually, you create it every time and on second time system shows you error, that "The specified child already has a parent. You must call removeView() on the child's parent first." Because dialog already exists.
If you wish to preserve everything as is, you should remove your dialog before every show() call. Check this for details.
But correct (for this issue) would be to move dialog creation code outside ItemClickListener.
I am cleaning up some code where a DialogFrament i supposed to diaplay items from an ArrayList (ref. "arr" in the code) and then the user can choose severeal items from it and then hit OK. This work fine, no problemo. But, only on Samsung Phones, the DialogFrament lists the item from the ArrayList twice. so, on all the other phone the list displays the values arr[0]->arr[n] but on Samsung(again ONLY on Samsung) the values are arr[0]->arr[n] + arr[0]->arr[n]. Since it's the same code for all android phones but the problem only occurs on Samsung Phones, im out of ideas.
A quick google search pointed me towards a difference in layout rules by Samsung depending on the resolution of their phone but it seeamed unlikely.
Have any of you heard about this before?
CODE FOR MY FRAGMENT
public ArrayList mSelectedItems;
public int type;
public boolean single = false;
int count;
boolean search;
public int single_item = -1;
public interface CategoriesDialogFragmentListener {
public void onOkay(ArrayList items, int type);
public void onCancel();
public void onSingleOkay(int item, int type);
}
CategoriesDialogFragmentListener mListener;
public void setType(int type_id) {
/*
1 = Category
2 = Genre
3 = Availability
*/
type = type_id;
}
public void setSearch(boolean isSearch) {
search = isSearch;
}
public void setList(ArrayList temp) {
mSelectedItems = temp;
}
public void isSingle(boolean is_single){
single = is_single;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the host
mListener = (CategoriesDialogFragmentListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Set the dialog title
CharSequence[] arr;
String title;
switch(type){
case 1:
title = "Välj kategori";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
single = true;
break;
case 2:
title = "Välj genre";
arr = MainActivity.GENRE_STRINGS.toArray(new CharSequence[MainActivity.GENRE_STRINGS.size()]);
single = false;
break;
case 3:
title = "Välj tillgängligheter";
arr = MainActivity.AVAIL_STRINGS.toArray(new CharSequence[MainActivity.AVAIL_STRINGS.size()]);
single = false;
break;
default:
title = "ett fel uppstod";
arr = MainActivity.CATEGORY_STRINGS.toArray(new CharSequence[MainActivity.CATEGORY_STRINGS.size()]);
}
if(!single) {
if(type == 2 && search == false) {
count = 0;
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
//Kod för att starta fragment med valda entiteter
/*
if(mSelectedItems != null || !mSelectedItems.isEmpty()){
for(Object e : mSelectedItems){
}
}
*/
if (isChecked) {
if (count < 5) {
mSelectedItems.add(which);
count++;
} else {
new android.app.AlertDialog.Builder(getActivity())
.setTitle(R.string.five)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
count--;
}
}
})
// Set the action buttons
.setPositiveButton("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
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}else{
builder.setTitle(title).setMultiChoiceItems(arr, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
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("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
mListener.onOkay(mSelectedItems, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});
}
} else {
builder.setTitle(title).setSingleChoiceItems(arr, -1, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
single_item = item;
}
})
.setPositiveButton("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
mListener.onSingleOkay(single_item, type);
}
})
.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
CategoriesDialogFragment.this.getDialog().cancel();
}
});;
}
return builder.create();
}
}
I've got a huge problem. When I had AlertBox everything was OK, but I would change it to custom dialog box with pretty good graphic.
With AlertBox it was displaying the current scores and highscore.
When I changed it to Custom Dialog box it's showing nothing.
CustomDialogClass.java
public class CustomDialogClass extends Dialog
{
public CustomDialogClass(Context context) {
super(context);
// TODO Auto-generated constructor stub
/** It will hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_dialog);
}
}
GameActivity.java (fragments with custom dialog box)
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
surfaceCreated = false;
stopDrawingThread();
}
public void customizeDialog() {
int highest = PrefUtil.getHighestScore(this);
String text = null;
if (currentPoint > highest) {
highest = currentPoint;
PrefUtil.setHighestScore(this, currentPoint);
} else {
}
text = "Current Points: " + currentPoint + "\nThe Best Score: " + highest;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Game Over");
builder.setMessage(text);
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
playSwooshing();
restart();
}
});
builder.setNegativeButton("Exit Game", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(GameActivity.this,Bye.class);
startActivity(intent);
playSwooshing();
finish();
}
});
builder.setCancelable(false);
alertDialog = builder.show();
}
and the other fragment:
private void onGameOver() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isFinishing()) {
soundPool.play(soundIds[SOUND_DIE], 0.5f, 0.5f, 1, 0, 1);
CustomDialogClass customizeDialog = new CustomDialogClass(GameActivity.this);
customizeDialog.show(); }
}
});
}
Where is a problem? Can someone fix it?
Now it's showing only my layout file, without any data.
Thanks!
It's not displaying your data because you're not setting your data. In your middle code fragment where you're creating your dialog using a Builder you're not using your custom dialog, so apparently that code is no longer being called. Likewise in your last fragment where you do create a custom dialog, you're not setting any the data.
See the documentation:
If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.
By default, the custom layout fills the dialog window, but you can still use AlertDialog.Builder methods to add buttons and a title.
Hey fellow Android Developers, Im having a issue currently with the below code. I am unable to figure out a way i can easily reference which Checkbox is clicked, Currently the code below is simply a Preference that when clicked, displays a AlertDialog with multiple Checkboxes.
The goal is do something specific when that Checkbox is checked, however i want to do something different possibly with each item.
Code
Preference checkboxalert = (Preference) findPreference("checkboxalert");
checkboxalert
.setOnPreferenceClickListener(new OnPreferenceClickListener() {
final CharSequence[] items = {" Easy "," Medium "," Hard "," Very Hard "};
final ArrayList<Integer> selectedItems=new ArrayList<Integer>();
public boolean onPreferenceClick(Preference preference) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Select The Difficulty Level");
builder.setMultiChoiceItems(items, null,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexSelected,
boolean isChecked) {
if (isChecked) {
//WHERE I WANT TO REFERENCE WHICH CHECKBOX IS CLICKED
selectedItems.add(indexSelected);
Log.i("Preference - Checkbox", "Something was clicked");
} else if (selectedItems.contains(indexSelected)) {
selectedItems.remove(Integer.valueOf(indexSelected));
}
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
}
});
dialog = builder.create();
dialog.show();
return true;
}
});
What's wrong with using the index?
#Override
public void onClick(DialogInterface dialog, int indexSelected,boolean isChecked)
{
if (isChecked) {
selectedItems.add(indexSelected);
//WHERE I WANT TO REFERENCE WHICH CHECKBOX IS CLICKED
switch (indexSelected)
{
case 0:
// do something if the first box is checked
break;
case 1:
// do something if the second box is checked
break;
...
}
}
It seems like this should work unless I am missing what you want.
I want to implement AlertDialog.Builder selected items click event. Below is what I have tried so far. I'm quite new to Android and I'm not sure how to access that event. How to implement the click event for each individual item in the list?
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class MakeCallAlertDialog {
public static AlertDialog.Builder getAlertDialog(String strArray[],
String strTitle, Activity activity) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(strTitle);
alertDialogBuilder.setItems(strArray, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int arg) {
// TODO Auto-generated method stub
}
});
return alertDialogBuilder;
}
}
Since you assigned an OnClickListener specific to that method, the int parameter is the position in the list:
Parameters
dialog The dialog that received the click.
which The button that was clicked (e.g. BUTTON1) or the position of the item clicked
This means inside your method, you should be able to do this:
public static AlertDialog.Builder getAlertDialog(final String strArray[],
String strTitle, final Activity activity) {
AlertDialog.Builder alertDialogBuilder =
new AlertDialog.Builder(activity);
alertDialogBuilder.setTitle(strTitle);
alertDialogBuilder.setItems(strArray,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(activity, strArray [which], Toast.LENGTH_SHORT).show();
//rest of your implementation
}
});
return alertDialogBuilder;
}
in onClick() event use switch statement to write click method for each button.
#Override
public void onClick(DialogInterface dialogInterface, int arg) {
// TODO Auto-generated method stub
switch (arg) {
case 0:
//you code for button at 0 index click
break;
case 1:
//you code for button at 1 index click
break;
default:
break;
}
}
Here, arg indicates the index of the button pressed. you can also access that button using strArray[arg]
Check my answer below if you are using single choice item selected for the strArray: Try this code
int selectedItem = 0;
// here take TempSelectOneTypeList = strArray
AlertDialog.Builder alt_bld = new AlertDialog.Builder(
Activity_Form_Data.this);
alt_bld.setTitle("Select One");
selectedItem = 0;
for (int j = 0; j < TempSelectOneTypeList.length; j++) {
if (txt_sub_lable2
.getText()
.toString()
.equals(TempSelectOneTypeList[j].toString())) {
selectedItem = j;
}
}
Log.i(TAG, "Selected Item is " + selectedItem);
alt_bld.setSingleChoiceItems(
ArraylistSelectOneTypeList.get(selected),
selectedItem,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int item) {
selectedItem = item;
// you can ocde here for the perticular selected item
}
});
alt_bld.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
txt_sub_lable2
.setText(""
+ TempSelectOneTypeList[selectedItem]
.toString());
}
});
alt_bld.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
AlertDialog alert = alt_bld.create();
alert.show();
Hope it will solve your problem