如何在android中获取特定列表视图项目的ID?

Posted

技术标签:

【中文标题】如何在android中获取特定列表视图项目的ID?【英文标题】:How to get id of particular item of listview in android? 【发布时间】:2015-01-22 02:25:53 【问题描述】:

我正在使用Listview 并设置多个项目,每个项目都有赞、分享和评论选项。 实际上,我已经成功获取了项目 ID 以及 TextViewsetText。但无法在特定项目的 Like Button Click 事件中获取项目 ID。 如何在Button点击事件中获取Listview中每个项目的项目ID?

MyAdapter 类的演示:

public class Adapter1 extends BaseAdapter implements OnClickListener 
    public ArrayList<HashMap<String, String>> arr = null;
    Context context = null;
    LayoutInflater layoutInflater = null;
    HashMap<String, String> getData = new HashMap<String, String>();

    String urlLike = null;
    TextView strId = null;

    public NewsFeedAdapter(Context context,
            ArrayList<HashMap<String, String>> arr) 
        this.context = context;
        this.arr= arr;
        layoutInflater = LayoutInflater.from(context);
    

    @Override
    public int getCount() 
        return arr.size();
    

    @Override
    public Object getItem(int position) 
        return arr.get(position);
    

    @Override
    public long getItemId(int position) 
        return position;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
        ViewHolder viewHolder = null;
        if (convertView == null) 
            convertView = layoutInflater.inflate(
                    R.layout.my_list_item, null);
            /** initialize ViewHolder */
            viewHolder = new ViewHolder();

            /** Initialize Widgets */
            /** Imageview */

            viewHolder.imgLike = (ImageView) convertView
                    .findViewById(R.id.imgLike);
            viewHolder.imgLike.setOnClickListener(this);

            viewHolder.imgComments = (ImageView) convertView
                    .findViewById(R.id.imgComments);
            viewHolder.imgComments.setOnClickListener(this);

            viewHolder.imgShare = (ImageView) convertView
                    .findViewById(R.id.imgShare);
            viewHolder.imgShare.setOnClickListener(this);

            /** TextView */
            viewHolder.txtId = (TextView) convertView
                    .findViewById(R.id.txtId);

            viewHolder.txtDescription = (TextView) convertView
                    .findViewById(R.id.txtDescription);

            getData = arr.get(position);
            viewHolder.txtId.setText(getData
                    .get(Fragment1.TAG_ID));

            viewHolder.txtDescription.setText(getData
                    .get(Fragment1.TAG_MESSAGE));

            convertView.setTag(viewHolder);

         else 
            viewHolder = (ViewHolder) convertView.getTag();
        

        convertView.setOnClickListener(new OnClickListener() 
            @Override
            public void onClick(View v)                

            
        );

        return convertView;
    

    /** ViewHolder Class */
    public class ViewHolder 
        ImageView imgLike = null, imgComments = null,
                imgShare = null;
        TextView txtId = null,txtDescription = null;
    

    @Override
    public void onClick(View view) 
        switch (view.getId()) 
        case R.id.imgLike:
            strId = ((TextView) view
                    .findViewById(R.id.txtId));
            System.out.println("On Click====="
                    + strId.getText().toString());

            urlLike = "http://www.example.com?id="
                    + strId.getText().toString() + "&user_id="
                    + myDetail.getUserId();

            new sendLikeData().execute();

            break;
        case R.id.imgComments:

            break;
        case R.id.imgShare:

            break;
        default:
            break;
        
    

    public class sendLikeData extends AsyncTask<Void, Void, Void> 
        protected void onPreExecute() 
            super.onPreExecute();
        

        @Override
        protected Void doInBackground(Void... arg0) 
            ServiceHandler sh = new ServiceHandler();
            String jsonStr = sh.makeServiceCall(urlLike, ServiceHandler.GET);
            Log.d("Response : Like", ">" + jsonStr);

            return null;
        

        protected void onPostExecute(Void result) 
            super.onPostExecute(result);
        ;
    

OutPut is, NullPointer Exception in System.out.println("On Click====="
                        + strId.getText().toString());.

xml文件是,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/masterLayout"
    android:layout_
    android:layout_
    android:layout_margin="@dimen/five_dp" >

    <TextView
        android:id="@+id/txtDescription"
        android:layout_
        android:layout_
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="@dimen/ten_dp"
        android:layout_marginRight="@dimen/ten_dp"
        android:layout_marginTop="@dimen/ten_dp" />

    <ImageView
        android:id="@+id/imgImage"
        android:layout_
        android:layout_
        android:layout_below="@+id/txtDescription"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="@dimen/ten_dp"
        android:layout_marginLeft="@dimen/ten_dp"
        android:layout_marginRight="@dimen/ten_dp"
        android:layout_marginTop="@dimen/ten_dp"
        android:background="@null"
        android:contentDescription="@string/content_description"
        android:src="@drawable/ic_launcher" />

    <LinearLayout
        android:layout_
        android:layout_
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/imgImage"
        android:background="@drawable/strip"
        android:baselineAligned="false"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <RelativeLayout
            android:layout_
            android:layout_
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/imgLike"
                android:layout_
                android:layout_
                android:layout_centerHorizontal="true"
                android:layout_centerInParent="true"
                android:contentDescription="@string/content_description"
                android:src="@drawable/like" />

            <TextView
                android:layout_
                android:layout_
                android:layout_alignTop="@+id/imgLike"
                android:layout_toRightOf="@+id/imgLike"
                android:background="@drawable/getbg"
                android:gravity="center"
                android:padding="@dimen/two_dp"
                android:textColor="@color/white"
                android:textSize="@dimen/ten_sp" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_
            android:layout_
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/imgComments"
                android:layout_
                android:layout_
                android:layout_centerHorizontal="true"
                android:layout_centerInParent="true"
                android:contentDescription="@string/content_description"
                android:src="@drawable/comments" />

            <TextView
                android:layout_
                android:layout_
                android:layout_toRightOf="@+id/imgComments"
                android:background="@drawable/getbg"
                android:gravity="center"
                android:padding="@dimen/two_dp"
                android:text="+1"
                android:textColor="@android:color/white"
                android:textSize="@dimen/ten_sp" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_
            android:layout_
            android:layout_weight="1" >

            <ImageView
                android:id="@+id/imgShare"
                android:layout_
                android:layout_
                android:layout_centerHorizontal="true"
                android:layout_centerInParent="true"
                android:contentDescription="@string/content_description"
                android:src="@drawable/share" />
        </RelativeLayout>
    </LinearLayout>

    <TextView
        android:id="@+id/txtId"
        android:layout_
        android:layout_
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_margin="@dimen/ten_dp"
        android:text="id"
        android:textSize="20dp" />

</RelativeLayout>

而 Logcat 是,

11-24 18:54:20.354: E/AndroidRuntime(7120): java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
11-24 18:54:20.354: E/AndroidRuntime(7120):     Adapter.onClick(Fragment.java:342)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.view.View.performClick(View.java:4562)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.view.View$PerformClick.run(View.java:18918)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.os.Handler.handleCallback(Handler.java:808)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.os.Handler.dispatchMessage(Handler.java:103)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.os.Looper.loop(Looper.java:193)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at android.app.ActivityThread.main(ActivityThread.java:5388)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at java.lang.reflect.Method.invokeNative(Native Method)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at java.lang.reflect.Method.invoke(Method.java:515)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:655)
11-24 18:54:20.354: E/AndroidRuntime(7120):     at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

android.widget.RelativeLayout 无法转换为 android.widget.TextView.... 移除 onclicklistener 的实现,并为每个可以工作的视图编写单独的视图监听器。我自己检查了示例代码... @Pratt TextView strId = (TextView) (((TextView) view.getParent()).findViewById(R.id.txtId)); System.out.println("!!!!!!!!!strId==="+strId.getText().toString()); @Pratt 这一行是放在 imgLike 按钮点击事件中。 @sri 是的,这是使用 TextView 时的错误 strId = (TextView) (((TextView) view.getParent()).findViewById(R.id.txtId)); System.out.println("!!!!!!!!!strId==="+strId.getText().toString()); 【参考方案1】:

试试下面的代码:

public class Adapter1 extends BaseAdapter implements OnClickListener 
    public ArrayList<HashMap<String, String>> arr = null;
    Context context = null;
    LayoutInflater layoutInflater = null;
    HashMap<String, String> getData = new HashMap<String, String>();

    String urlLike = null;
    TextView strId = null;

    public NewsFeedAdapter(Context context,
            ArrayList<HashMap<String, String>> arr) 
        this.context = context;
        this.arr= arr;
        layoutInflater = LayoutInflater.from(context);
    

    @Override
    public int getCount() 
        return arr.size();
    

    @Override
    public Object getItem(int position) 
        return arr.get(position);
    

    @Override
    public long getItemId(int position) 
        return position;
    

    @Override
    public View getView(int position, View convertView, ViewGroup parent) 
        ViewHolder viewHolder = null;
        if (convertView == null) 
            convertView = layoutInflater.inflate(
                    R.layout.my_list_item, null);
            /** initialize ViewHolder */
            viewHolder = new ViewHolder();

            /** Initialize Widgets */
            /** Imageview */

            viewHolder.imgLike = (ImageView) convertView
                    .findViewById(R.id.imgLike);


            viewHolder.imgComments = (ImageView) convertView
                    .findViewById(R.id.imgComments);
            viewHolder.imgComments.setOnClickListener(this);

            viewHolder.imgShare = (ImageView) convertView
                    .findViewById(R.id.imgShare);
            viewHolder.imgShare.setOnClickListener(this);

            /** TextView */
            viewHolder.txtId = (TextView) convertView
                    .findViewById(R.id.txtId);

            viewHolder.txtDescription = (TextView) convertView
                    .findViewById(R.id.txtDescription);

            getData = arr.get(position);
            viewHolder.txtId.setText(getData
                    .get(Fragment1.TAG_ID));

            viewHolder.txtDescription.setText(getData
                    .get(Fragment1.TAG_MESSAGE));

            convertView.setTag(viewHolder);

         else 
            viewHolder = (ViewHolder) convertView.getTag();
        

        convertView.setOnClickListener(new OnClickListener() 
            @Override
            public void onClick(View v)                

            
        );

         viewHolder.imgLike.setOnClickListener(new OnClickListener() 
            @Override
            public void onClick(View v)                
                strId=arr.get(position).getId();//or whatever you want to do do here.
            
        );

        return convertView;
    

    /** ViewHolder Class */
    public class ViewHolder 
        ImageView imgLike = null, imgComments = null,
                imgShare = null;
        TextView txtId = null,txtDescription = null;
    

【讨论】:

不获取 getId();在 strId=arr.get(position).getId(); @Reena 我的办公时间结束了,你可以发邮件给我源,让我解决并回复你。 @Reena 没关系,欢迎您,如果上面的代码工作正常,那么请接受并投票,祝您编码愉快!!!【参考方案2】:

试试这个:

strId = (TextView) view.getParent().findViewById(R.id.txtId);

这将解决您的崩溃问题,但您需要重新考虑您的设计。

【讨论】:

【参考方案3】:

你需要做的是在 diff 视图上设置 Diff onclick 监听器

viewHolder.txtDescription.setTag(R.id.txtDescription,position);
viewHolder.txtDescription.setOnClickListener(new OnClickListener()     
    @Override
    public void onClick(View v) 
        int position_clicked=(Integer)v.getTag();               
    
);

对您想要设置监听器的每个视图重复此操作

【讨论】:

我正在使用 int position_clicked=(Integer)v.getTag(); 但它给出了空指针异常。 setTag(R.id.txtDescription,position) 对每个视图使用这个,使用 R.id.txtDescription(即每个视图的 id 作为键) 请帮帮我。我使用 viewHolder.imgMyNewsFeedLike.setTag(R.id.imgMyNewsFeedLike,position); viewHolder.imgMyNewsFeedLike.setOnClickListener(new OnClickListener() @Override public void onClick(View v) int position_clicked=(Integer)v.getTag(); System.out.println("!!!!!!!!!! !id====="+position_clicked); );它给出空指针异常。我在 View getView() 方法中使用这个。【参考方案4】:

需要在getView()中初始化strId

在下面的代码中,它无法根据“视图”对象对其进行初始化,因此你得到了空指针。

case R.id.imgLike:
    strId = ((TextView) view.findViewById(R.id.txtId));

如果您觉得答案有用,请标记为已解决。

【讨论】:

【参考方案5】:

您也可以在适配器类中使用 onClickListener。

看看这个示例代码

viewHolder.imgLike = (ImageView) convertView.findViewById(R.id.imgLike);
viewHolder.imgLike.setOnClickListener(new OnClickListener() 

    @Override
    public void onClick(View arg0) 
        // TODO Auto-generated method stub
        String id = getData.get(Fragment1.TAG_ID);
    
);

【讨论】:

我是这个但它再次得到 NullPointerException【参考方案6】:

试试这样,

@Override
public View getView(int position, View convertView, ViewGroup parent) 
    ViewHolder viewHolder = null;
    if (convertView == null) 
        convertView = layoutInflater.inflate(
                R.layout.my_list_item, null);
        /** initialize ViewHolder */
        viewHolder = new ViewHolder();

        /** Initialize Widgets */
        /** Imageview */

        viewHolder.imgLike = (ImageView) convertView
                .findViewById(R.id.imgLike);
        viewHolder.imgLike.setOnClickListener(this);
        viewHolder.imgLike.setTag(position);

        viewHolder.imgComments = (ImageView) convertView
                .findViewById(R.id.imgComments);
        viewHolder.imgComments.setOnClickListener(this);

        viewHolder.imgShare = (ImageView) convertView
                .findViewById(R.id.imgShare);
        viewHolder.imgShare.setOnClickListener(this);

        /** TextView */
        viewHolder.txtId = (TextView) convertView
                .findViewById(R.id.txtId);

        viewHolder.txtDescription = (TextView) convertView
                .findViewById(R.id.txtDescription);

        getData = arr.get(position);
        viewHolder.txtId.setText(getData
                .get(Fragment1.TAG_ID));

        viewHolder.txtDescription.setText(getData
                .get(Fragment1.TAG_MESSAGE));

        convertView.setTag(viewHolder);

     else 
        viewHolder = (ViewHolder) convertView.getTag();
    

    convertView.setOnClickListener(new OnClickListener() 
        @Override
        public void onClick(View v)                

        
    );

    return convertView;


@Override
    public void onClick(View view) 
        switch (view.getId()) 
        case R.id.imgLike:

        View view = listview.getAdapter().getView(((ImageView)v).getTag(), null, listview);
            txtId = (TextView) view.findViewById(R.id.txtId);

            System.out.println("On Click====="
                    + strId.getText().toString());

            urlLike = "http://www.example.com?id="
                    + strId.getText().toString() + "&user_id="
                    + myDetail.getUserId();

            new sendLikeData().execute();

            break;
        case R.id.imgComments:

            break;
        case R.id.imgShare:

            break;
        default:
            break;
        
    

【讨论】:

@Pratt,我正在使用 strId = ((TextView)v);然后给出 java.lang.ClassCastException 之类的错误:android.widget.ImageView cannot be cast to android.widget.TextView @Akash 在适配器类中声明列表视图在哪里? 把你的适配器放在你的列表类中,从那里你可以得到列表视图 视图视图 = listview.getAdapter().getView(((ImageView)v).getTag(), null, listview);在此如何获取listview? 只需将您的适配器代码放在您声明 ListView 的主类中

以上是关于如何在android中获取特定列表视图项目的ID?的主要内容,如果未能解决你的问题,请参考以下文章

单击列表视图项时检索的值

如何从列表视图中的项目单击中获取歌曲在android中

Android如何从同一个数组中仅显示列表视图中的某些项目?

android listview 获取所选项目

如何在单击android中的listview项目时从数据库中获取id

如何在列表视图的每个项目上加载 json 数据并显示在 android 的另一个活动中获取的数据?