Andrew Quebe
Andrew Quebe

Reputation: 2293

Issue with onLongClickListener and Position

So I have a listview full of cards and I want to longPress each one and be able to share the text that is on the card. I've done research about longPress events and this is what I came up with:

Setting listener on listview

lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        showOptionsMenu(position);
        return false;
    }
});

And here is the showOptionsMenu method

public void showOptionsMenu(int position) {
    new AlertDialog.Builder(this).setCancelable(true).setItems(R.array.longClickItems,
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialoginterface, int i) {
                TextView tvMessage = (TextView) findViewById(R.id.tvContent);
                TextView tvName = (TextView) findViewById(R.id.tvTitle);

                String message = tvMessage.getText().toString();
                String name = tvName.getText().toString();

                Intent sharingIntent = new Intent(Intent.ACTION_SEND);
                sharingIntent.setType("text/plain");
                String shareBody = "Message:\n" + message + "\n" + "\nSigned by:\n" + name;
                shareBody = shareBody.replace("-", "");
                sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
                startActivity(Intent.createChooser(sharingIntent, "Send To:"));
            }
        }).show();
}

Now, all this works great except there's one problem: every time I long press, no matter the list item position, the text retrieved is always from the first item in the list. I tried some of the getPosition methods in the listview class but nothing worked...help is appreciated!

Upvotes: 1

Views: 518

Answers (2)

nem035
nem035

Reputation: 35491

You are not using the input position in showOptionsMenu(int position).

In the OnLongClick, the parameters are:

parent       The AbsListView where the click happened
view         The view within the AbsListView that was clicked
position     The position of the view in the list
id           The row id of the item that was clicked

You can use the:

parent.getItemAtPosition(position)

to obtain the item at that position. Then you can pass that item to your other method or perhaps Toast the card name.

Or directly use the view parameter which is the view that was clicked and then display what you want.

Upvotes: 3

suitianshi
suitianshi

Reputation: 3340

You should call getItem on the adapter and pass the object(that is, the data at position of the data array ) to showOptionsMenu

Upvotes: 1

Related Questions