【问题标题】:How to get the position of a row in a listview?如何获取列表视图中一行的位置?
【发布时间】:2019-12-07 10:53:48
【问题描述】:

任何人都可以帮助我单击时如何从列表视图中存储行的值位置? 我想在另一个类上使用 onPostExecute 中的值。 提前感谢您的时间。 这是我的代码。

 @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        if (view == null) {
            view = LayoutInflater.from(c).inflate(R.layout.model, viewGroup, false);
        }
       ...
        final Pending s = (Pending) this.getItem(i);
       ...

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

*//here is where I want to get the position to use on my updateData()'s onPostExecute*

                final String id = 2;
                String link = "http://abcabcabc.com/abc.php?id=" + id;
                new updateData().execute(link);
            }
        });
        return view;
    }

另外,如何在 onPostExecute 中调用它来显示一些数据?

【问题讨论】:

  • 你可以从你的适配器类中得到它。
  • @MdMobinurRahman 我现在得到了该行的值。你能建议我如何在我的 onPostExecute 中使用它吗?提前致谢。是否可以将其存储在 Log.i 中?对不起。我是新手。

标签: android android-listview


【解决方案1】:

行的位置是你getView方法中的参数i

@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
    //i is the position of the row
}

为了在AsyncTaskonPostExecute 方法中使用行的位置,您需要将行位置作为参数传递给“updateData”类。

但是,问题是AsyncTask 只能接受一种类型的数据作为参数,目前它只能接受字符串。

要解决此问题并能够同时传递 URL(字符串)和 id/行位置(整数),您可以创建一个类(使用更好的名称来表示您对链接所做的操作):

public class DetailLink {
    private String link;
    private int id;

   //getters and setters
}

然后,在“updateData”类中,将Params 类型参数更改为DetailLink 类型而不是String。这意味着您的doInBackground 方法将接受DetailLink 作为参数。为了存储 id 以便可以使用onPostExecute 方法,请将其保存为“updateData”类的实例变量。

 private class UpdateDataTask extends AsyncTask<DetailLink, Void, Void> {
     private int myId;

     protected void doInBackground(DetailLink... detailLink) {
         myId = detailLink.getId();
         String url = detailLink.getLink();
         //do your task here
     }

     protected void onPostExecute() {
         //do something with the myId instance variable
     }
 }

最后,在您的 getView 方法中,您可以创建一个新的 DetailLink 并将其传递给您的 execute 方法:

DetailLink detailLink = new DetailLink();
detailLink.setId(i);
detailLink.setLink(link);
new updateData().execute(detailLink);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多