如何在ListView上长按时传递变量?

发布于 2024-10-26 01:50:28 字数 5083 浏览 1 评论 0原文

我会有列表视图和里面的很多项目。我希望用户可以长按项目并将其设置为收藏夹。为此,我需要长按此菜单获取数据库 ID。

我有以下代码

@Override
public void onCreateContextMenu(ContextMenu menu, 
                              View v, 
                              ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);

menu.setHeaderTitle("Favorite");
menu.add(0, REMOVE_TODO, Menu.NONE, R.string.favorit_add);
}

它工作得很好...但我想做的是获取所选项目的文本和数据库 ID。

因此,我想写“Favorite”代替“Favorite”:Item1。

如果有人能提供帮助,我将不胜感激。

这是我的适配器的代码...我实际上使用了示例的适配器。

    package com.TVSpored;

import android.content.Context;
import java.util.*;
import android.view.*;
import android.widget.*;

public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {

  int resource;

  public ToDoItemAdapter(Context _context, 
                             int _resource, 
                             List<ToDoItem> _items) {
    super(_context, _resource, _items);
    resource = _resource;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LinearLayout todoView;

    ToDoItem item = getItem(position);

    String taskString = item.getTask();
    String icon_name = item.getCreated();
    int fav = item.getFavorite();

    if (convertView == null) {
      todoView = new LinearLayout(getContext());
      String inflater = Context.LAYOUT_INFLATER_SERVICE;
      LayoutInflater vi = (LayoutInflater)getContext().getSystemService(inflater); 
      vi.inflate(resource, todoView, true);
    } else {
      todoView = (LinearLayout) convertView;
    }

    ImageView favView = (ImageView)todoView.findViewById(R.id.rowImgFav);
    ImageView channelView = (ImageView)todoView.findViewById(R.id.rowImg);
    TextView channelName = (TextView)todoView.findViewById(R.id.row);

    //dateView.setText(dateString);

    channelView.setImageResource(getContext().getResources().getIdentifier("com.TVSpored:drawable/channels_"+icon_name , null, null));

    channelName.setText(taskString);

    if(fav == 0)
    {
        favView.setImageResource(R.drawable.sys_srcek_disabled);
    }
    else
    {
        favView.setImageResource(R.drawable.sys_srcek);
    }
    return todoView;
  }
  }

进一步我的项目

package com.TVSpored;

import java.text.SimpleDateFormat;

public class ToDoItem {

  String task;
  String created;
  Integer fav;
  Integer id;

  public String getTask() {
    return task;
  }

  public String getCreated() {
    return created;    
  }

  public Integer getFavorite()
  {
      return fav;
  }

  public Integer getID()
  {
      return id;
  }

  public ToDoItem(String _task, String _created, int _fav, int _id) {
    task = _task;
    created = _created;
    fav = _fav;
    id = _id;
  }

  }

这是主活动类中的代码

 @Override
 public void onCreateContextMenu(ContextMenu menu, 
                              View v, 
                              ContextMenu.ContextMenuInfo menuInfo) {
 super.onCreateContextMenu(menu, v, menuInfo);


 menu.setHeaderTitle("Urejanje kanala");
 menu.add(0, REMOVE_TODO, Menu.NONE, R.string.favorit_add); 
 // static final private int REMOVE_TODO = Menu.FIRST + 1; // defined ad the begining
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 super.onOptionsItemSelected(item);

 AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
 int arrayAdapterPosition = menuInfo.position;

 ToDoItem todoItem = (ToDoItem)aa.getItem(arrayAdapterPosition);
 String task = todoItem.getTask();
 int id = todoItem.getID();

 int index = myListView.getSelectedItemPosition();
 aa.getItemId(index);

 changeFavorite(id);
 return true;
 }

这是 updateArray 函数(在更改时调用)

private void updateArray() {
  toDoListCursor.requery();

  todoItems.clear();
  int j = 0;
  if (toDoListCursor.moveToFirst())
    do 
    { 
      String task =            toDoListCursor.getString(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_NAME));
      String created = toDoListCursor.getString(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_EPG_NAME));
      int fav = toDoListCursor.getInt(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_EPG_NAME));
      int id = toDoListCursor.getInt(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_ID));

      ToDoItem newItem = new ToDoItem(task, created, fav, id);
      todoItems.add(0, newItem);
      j++;
    } 
    while(toDoListCursor.moveToNext());

  aa.notifyDataSetChanged();
}

和填充函数...

private void populateTChannels() {
// Get all the todo list items from the database.
toDoListCursor = toDoDBAdapter. getAllToDoItemsCursor();
if((toDoListCursor.getCount() == 0) || !toDoListCursor.moveToFirst())
{
    toDoDBAdapter.populateDB();
}

if(toDoDBAdapter.ChannelsArray.length > toDoListCursor.getCount())
{
    toDoDBAdapter.populateDBWhitCheck();
}
toDoListCursor = toDoDBAdapter. getAllToDoItemsCursor();
startManagingCursor(toDoListCursor);

// Update the array.
updateArray();
}

I would have listview and a lot of items inside. I want that user can long press on item and set it as Favorite. To do that, I need to get DB id to this menu on long press.

I have the following code

@Override
public void onCreateContextMenu(ContextMenu menu, 
                              View v, 
                              ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);

menu.setHeaderTitle("Favorite");
menu.add(0, REMOVE_TODO, Menu.NONE, R.string.favorit_add);
}

It works just fine... But what I want to do is to get text and database id of selected item.

So insetead of "Favorite" I would like to write Favorite: Item1.

If anyoune could help I would be thankful.

Here is a code for my adapter... I actually used example's adapter.

    package com.TVSpored;

import android.content.Context;
import java.util.*;
import android.view.*;
import android.widget.*;

public class ToDoItemAdapter extends ArrayAdapter<ToDoItem> {

  int resource;

  public ToDoItemAdapter(Context _context, 
                             int _resource, 
                             List<ToDoItem> _items) {
    super(_context, _resource, _items);
    resource = _resource;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LinearLayout todoView;

    ToDoItem item = getItem(position);

    String taskString = item.getTask();
    String icon_name = item.getCreated();
    int fav = item.getFavorite();

    if (convertView == null) {
      todoView = new LinearLayout(getContext());
      String inflater = Context.LAYOUT_INFLATER_SERVICE;
      LayoutInflater vi = (LayoutInflater)getContext().getSystemService(inflater); 
      vi.inflate(resource, todoView, true);
    } else {
      todoView = (LinearLayout) convertView;
    }

    ImageView favView = (ImageView)todoView.findViewById(R.id.rowImgFav);
    ImageView channelView = (ImageView)todoView.findViewById(R.id.rowImg);
    TextView channelName = (TextView)todoView.findViewById(R.id.row);

    //dateView.setText(dateString);

    channelView.setImageResource(getContext().getResources().getIdentifier("com.TVSpored:drawable/channels_"+icon_name , null, null));

    channelName.setText(taskString);

    if(fav == 0)
    {
        favView.setImageResource(R.drawable.sys_srcek_disabled);
    }
    else
    {
        favView.setImageResource(R.drawable.sys_srcek);
    }
    return todoView;
  }
  }

And furtherer my Item

package com.TVSpored;

import java.text.SimpleDateFormat;

public class ToDoItem {

  String task;
  String created;
  Integer fav;
  Integer id;

  public String getTask() {
    return task;
  }

  public String getCreated() {
    return created;    
  }

  public Integer getFavorite()
  {
      return fav;
  }

  public Integer getID()
  {
      return id;
  }

  public ToDoItem(String _task, String _created, int _fav, int _id) {
    task = _task;
    created = _created;
    fav = _fav;
    id = _id;
  }

  }

Here is a code in main activity class

 @Override
 public void onCreateContextMenu(ContextMenu menu, 
                              View v, 
                              ContextMenu.ContextMenuInfo menuInfo) {
 super.onCreateContextMenu(menu, v, menuInfo);


 menu.setHeaderTitle("Urejanje kanala");
 menu.add(0, REMOVE_TODO, Menu.NONE, R.string.favorit_add); 
 // static final private int REMOVE_TODO = Menu.FIRST + 1; // defined ad the begining
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
 super.onOptionsItemSelected(item);

 AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
 int arrayAdapterPosition = menuInfo.position;

 ToDoItem todoItem = (ToDoItem)aa.getItem(arrayAdapterPosition);
 String task = todoItem.getTask();
 int id = todoItem.getID();

 int index = myListView.getSelectedItemPosition();
 aa.getItemId(index);

 changeFavorite(id);
 return true;
 }

Here is updateArray function (called on change)

private void updateArray() {
  toDoListCursor.requery();

  todoItems.clear();
  int j = 0;
  if (toDoListCursor.moveToFirst())
    do 
    { 
      String task =            toDoListCursor.getString(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_NAME));
      String created = toDoListCursor.getString(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_EPG_NAME));
      int fav = toDoListCursor.getInt(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_EPG_NAME));
      int id = toDoListCursor.getInt(toDoListCursor.getColumnIndex(ToDoDBAdapter.KEY_ID));

      ToDoItem newItem = new ToDoItem(task, created, fav, id);
      todoItems.add(0, newItem);
      j++;
    } 
    while(toDoListCursor.moveToNext());

  aa.notifyDataSetChanged();
}

and a populate function...

private void populateTChannels() {
// Get all the todo list items from the database.
toDoListCursor = toDoDBAdapter. getAllToDoItemsCursor();
if((toDoListCursor.getCount() == 0) || !toDoListCursor.moveToFirst())
{
    toDoDBAdapter.populateDB();
}

if(toDoDBAdapter.ChannelsArray.length > toDoListCursor.getCount())
{
    toDoDBAdapter.populateDBWhitCheck();
}
toDoListCursor = toDoDBAdapter. getAllToDoItemsCursor();
startManagingCursor(toDoListCursor);

// Update the array.
updateArray();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉月流沐 2024-11-02 01:50:28

您传递的 ContextMenu.ContextMenuInfo 包含有关单击列表中哪个项目的信息。您也许可以使用它来获取您需要的信息。

更新:

有点像 dziobas 在他的回答中提到的那样,您可以执行类似的操作来了解所选项目在适配器中的位置:

AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
long arrayAdapterPosition = menuInfo.position;

现在您知道了位置,并且可以从您的 ArrayAdapter。如果您将此 ArrayAdapter 实例存储在成员变量中(在本示例中我将其命名为 myArrayAdapter),则可以使用 ArrayAdapter.getItem(intposition) 继续获取该项目code>:

ToDoItem todoItem = (ToDoItem)myArrayAdapter.getItem(arrayAdapterPosition);
String task = todoItem.getTask();
int id = todoItem.getId();

您现在可以继续设置菜单标题标题,如下所示:

menu.setHeaderTitle("Favorite: " + task + Integer.toString(id));

The ContextMenu.ContextMenuInfo you get passed contains information about which item in the list was clicked. You can probably use this to get the information you need.

Update:

Somewhat like dziobas mentions in his answer you can do something like this to get to know which position the selected item has in your adapter:

AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
long arrayAdapterPosition = menuInfo.position;

Now you know the position, and can fetch it from your ArrayAdapter. If you have this ArrayAdapter instance stored in a member variable (in this example I have named it myArrayAdapter), you can then proceed to get the item with ArrayAdapter.getItem(int position):

ToDoItem todoItem = (ToDoItem)myArrayAdapter.getItem(arrayAdapterPosition);
String task = todoItem.getTask();
int id = todoItem.getId();

You could now proceed to set the menu header title as follows:

menu.setHeaderTitle("Favorite: " + task + Integer.toString(id));
狼亦尘 2024-11-02 01:50:28

如果您的适配器支持获取 Id,那么它应该如下所示:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
    long id = menuInfo.id;
    ...

If your adapter supports getting Id, so it should look like this:

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
    long id = menuInfo.id;
    ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文