here is the code. When I long click on an item and dont drag my finger away from it, the menu still pops up, but it also activates my onClick listener. I have no idea why. I have tried looking for solutions online, and I only found something that told me to check the return statement. I am returning True, so I do not know what else to do.
listView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(AddClaim.this, "Clicked "+list.get(position), Toast.LENGTH_SHORT).show();
//adapter expenses
setContentView(R.layout.add_expense);
ListView expView = (ListView) findViewById(R.id.ExpenseListView);
Collection<Expense> expenses = list.get(position).getExpenses();
final ArrayList<Expense> expense = new ArrayList<Expense>(expenses);
final ArrayAdapter<Expense> expAdap = new ArrayAdapter<Expense>(AddClaim.this, android.R.layout.simple_list_item_1, expense);
expView.setAdapter(expAdap);
}
});
//LONG CLICK FUNCTIONS
listView.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
final int finalPosition = position;
PopupMenu popup = new PopupMenu(AddClaim.this, view);
popup.getMenuInflater().inflate(R.menu.add_claim, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
//DELETE button check.
if (item.getTitle().equals("Delete")){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(finalPosition).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(finalPosition);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}//end of delete button check
//START of ADD EXPENSE check
if (item.getTitle().equals("Add Expense")){
Intent intent = new Intent(AddClaim.this, ExpenseAdd.class);
intent.putExtra("somename", finalPosition);
startActivity(intent);
}
//end of add expense check
return true;
}
});
popup.show();
return false;
}
});
}
Look carefully at your code,and count your braces but read my comments
listView.setOnItemLongClickListener(new OnItemLongClickListener(){ //function starts here
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) { // longclick starts here
final int finalPosition = position;
PopupMenu popup = new PopupMenu(AddClaim.this, view); // your menu code starts here
popup.getMenuInflater().inflate(R.menu.add_claim, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
//DELETE button check.
if (item.getTitle().equals("Delete")){
AlertDialog.Builder adb = new AlertDialog.Builder(AddClaim.this);
adb.setMessage("Delete "+ list.get(finalPosition).toString()+"?");
adb.setCancelable(true);
adb.setPositiveButton("Delete",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
Claim claim = list.get(finalPosition);
ClaimListController.getClaimList().deleteClaim(claim);
}
});
adb.setNegativeButton("Cancel",new OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.show();
}//end of delete button check
//START of ADD EXPENSE check
if (item.getTitle().equals("Add Expense")){
Intent intent = new Intent(AddClaim.this, ExpenseAdd.class);
intent.putExtra("somename", finalPosition);
startActivity(intent);
}
//end of add expense check
return true; // you only return true if onmenu item is clicked.. which is too late
}
});
popup.show(); // and your menu code ends here, because this is where it is shown..
return false; // you are returning false.. this is {star line}
} //longclick ends here
}); //function ends here
}
{start line} should return true
Related
I'm attempting to make an alert dialog remove an item in a ListView but I can't find a solution to how I do it.
Here is my code:
contactsListView.setLongClickable(true);
contactsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(ContactsActivity.this);
builder.setTitle("Contact Removal");
builder.setMessage("Are you sure you want to remove this contact?");
builder.setCancelable(false);
builder.setPositiveButton("Yes, I'm sure!", new HandleAlertDialogListener());
builder.setNegativeButton("No, I've changed my mind", new HandleAlertDialogListener());
AlertDialog dialog = builder.create();
dialog.show();
return true;
}
});
Here is my HandleAlertDialogListener()
private class HandleAlertDialogListener implements DialogInterface.OnClickListener {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
the problem is that I can't refer to the position of the item I want removed.
Another question is what are the which values for the dialog's buttons?
Any help would be appreciated.
In your onItemLongClick() make your position parameter final , then create your alert dialog like this :
new AlertDialog.Builder(this).setTitle("Delete").setMessage("Review").setPositiveButton(R.string.positive_delete, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int id) {
// use position here.
}
}).setNegativeButton(R.string.negative_reask, new DialogInterface.OnClickListener() {
#Override
public void onClick(final DialogInterface dialog, final int id) {
dialog.dismiss();
}
}).create().show();
Hope this helps!
I guess you have an Adapter to show items in a ListView?
If so, you should delete an item like I said:
myDataList.remove(position);
myAdapter.notifyDataSetChanged();
Where position is an attribute in this method:
onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
I am new to android. I want to have a dialog box with positive and negative buttons when i click on a gridview item. Right now when i click on an item, it populates another activity with the information of the item that i clicked on.
For example, using putExtra and getExtras , populating the activity works great. Now all i want is that instead of the action being performed on gridView click, i want the action being performed on the ok button of the Alertdialog box.
How should i set the gridview.setOnCLickListener so that it pops up an alertDialog Box when an item is clicked??
gridView.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
gridView.setClickable(true);
item= (Hotel) parent.getItemAtPosition(position);
String names = item.getName();
Intent i=new
Intent(HotelList.this,UserViewActivity.class);
i.putExtra("names",names);
startActivity(i);
}
});
Try out the following code:
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {
item= (Hotel) parent.getItemAtPosition(position);
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(false);
dialog.setTitle("Your Title");
dialog.setMessage("Your Message" );
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
String names = item.getName();
Intent i= new Intent(HotelList.this,UserViewActivity.class);
i.putExtra("names",names);
startActivity(i);
alert.cancel();
}
})
.setNegativeButton("Cancel ", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
alert.cancel();
}
});
final AlertDialog alert = dialog.create();
alert.show();
}
});
Hope this helps.
First, remove gridView.setClickable(true). It's simply not necessary. Second, You can create the Dialog in your code:
AlertDialog ad = new AlertDialog.Builder(this).setContentView(R.layout.activity_dialog).show();
I want to delete items on a listView when longpressed. In this code you can add (with edittext) a list item with Button, as you can see below.
I have been unable to write the code for deleting them with a long press. What should I do?
Ideally, a long press will bring up a menu and user can touch and delete the section they want.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.addButton);
listView = (ListView) findViewById(R.id.listView);
listItems = new ArrayList<String>();
listItems.add("First Item - added on Activity Create");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_LONG)
.show();
}
});
}
Try this one :
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long arg3) {
adapter.remove(data[position]);//position of the item you click
adapter.notifyDataSetChanged();
return false;
}
});
You can do it with animation:
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long arg3) {
adapter.remove(data[position]);//position of the item you click
adapter.notifyItemRemoved(position);
return false;
}
});
Use this for listview item delete on long click and it should be display alert dialog when you delete any item from list view
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
removeItemFromList(position);
return true;
}
private void removeItemFromList(int position) {
final int deletePosition = position;
AlertDialog.Builder alert = new AlertDialog.Builder(
this);
alert.setTitle("Delete");
alert.setMessage("Do you want delete this item?");
alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TOD O Auto-generated method stub
// main code on after clicking yes
songsList.remove(deletePosition);
songAdapter.notifyDataSetChanged();
songAdapter.notifyDataSetInvalidated();
}
});
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alert.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);
}
I'm trying to create a dynamic listview. I can add an item but i can't remove it right now. The code actually it's very simple and every guide i saw are too much complicated for me and my code. I want something simple to add in my MainActivity to remove the item selceted. I don't care in which way, swipe like gmail or by click or any other way.. I just want i simple way to remove an element of the list. This is the Activity
public class MainActivity extends Activity {
private EditText etInput;
private Button btnAdd;
private ListView lvItem;
private ArrayList<String> itemArrey;
private ArrayAdapter<String> itemAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setUpView();
}
private void setUpView() {
// TODO Auto-generated method stub
etInput = (EditText)this.findViewById(R.id.editText_input);
btnAdd = (Button)this.findViewById(R.id.addbtn);
lvItem = (ListView)this.findViewById(R.id.listView_items);
itemArrey = new ArrayList<String>();
itemArrey.clear();
itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
lvItem.setAdapter(itemAdapter);
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addItemList();
}
});
etInput.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_ENTER) {
addItemList();
}
return true;
}
});
}
protected void addItemList() {
if (isInputValid(etInput)) {
itemArrey.add(0,etInput.getText().toString());
etInput.setText("");
itemAdapter.notifyDataSetChanged();
}
}
protected boolean isInputValid(EditText etInput2) {
// TODO Auto-generatd method stub
if (etInput2.getText().toString().trim().length()<1) {
etInput2.setError("Insert a value");
return false;
} else {
return true;
}
}
}
Is it possible insert some part of code to remove an item inside my activity code? Thanks
try this, While ListView item long ClickListener you can do it
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
int position, long id) {
// TODO Auto-generated method stub
AlertDialog.Builder adb = new AlertDialog.Builder(
YourActivity.this);
adb.setTitle("Are you sure want to delete this item");
adb.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
}
});
adb.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
adb.show();
return false;
}
});
This should help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
Put this method in your onCreate:
lvItem .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
});
}
Of course it is possible.
ArrayList.html#remove
Or if you don't know the index just iterate through the list.
Calling remove in foreach loop in Java
Do this way..
lvItem.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long id) {
itemArrey.remove(position);
itemAdapter.notifyDataSetChanged();
return true;
}
});
To delete item from list just do one thing, get onLongClickListener of listView.
Then open the context menu which has two options
Delete
Cancel
When user picks first item delete it from list. Then call listadapter notify datasetChanged method.
Use this library, I used this and it works very fine, if you prefer Swipe try this:
https://github.com/47deg/android-swipelistview
Try below code:
single click:
listview .setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
showDialog(int position);
});
}
public void showDialog(int position){
AlertDialog alertDialog;
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
alertDialog = builder.create();
alertDialog.setOnDismissListener(new myOnDismissListener());
alertDialog.setTitle(TITLE OF DIALOG);
alertDialog.setMessage(MESSAGE YOU WANT TO SHOW IN DIALOG);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
YOUR ARRAY.remove(position);
YOUR ADAPTER.notifyDataSetChanged();
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertDialog.show();
}