ListView getChildAt为不可见的元素提供NullPointer(Android) [英] ListView getChildAt giving NullPointer for not visible elements (Android)

查看:59
本文介绍了ListView getChildAt为不可见的元素提供NullPointer(Android)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我从列表视图中选择一项在创建活动时不可见的项目时,它将引发异常,因为不可见的项为null.如您所见,我已经知道问题为什么会导致异常,并且我感谢为我提供解决问题的技巧的人.这是代码.

When I select one of the items from the listview that is not visible when the activity is created it throws an exception becuase those that are not visible are null. As you see, I already know why the problem gives the exception and I would thank the one that gives me the tip for solving it. Here's the code.

public void myFunction(View view) {
        int i, i2 = 0;
        // get the row the clicked button is in
        ListView lerroa = (ListView) view.getParent();
        i = lerroa.getPositionForView(view);
        System.out.println(i + 1);


        LinearLayout ll = (LinearLayout) lerroa.getChildAt(i);
        TextView pedido = (TextView) ll.getChildAt(0);
}

有没有更简单的方法来对被单击的项目进行textview?

Any easier way of taking the textview at the item that has been clicked on?

推荐答案

我已经解决了问题.

为了也显示列表视图中不可见的项目,那些导致NullPointers的项目,我替换了导致应用程序崩溃的代码行.在这里:

In order to show also the items of the list view that were not visible, those that caused the NullPointers, I've replaced the line of code which crashed the app. Here it is:

替换:

LinearLayout ll = (LinearLayout) lerroa.getChildAt(i);

为此:

LinearLayout ll = (LinearLayout) lerroa.getChildAt(i -lerroa.getFirstVisiblePosition()).findViewById(R.id.LinearLayout3);

getVisiblePosition允许我们玩在LinearLayout上显示的第一项,因此避免了任何NullPointer.

getVisiblePosition allows us playing with the first item shown at the LinearLayout and so avoids any NullPointer.

我知道这有点伪劣,但这不是编码我想要实现的最佳方法.尽管如此,我已经在互联网上看到很多次相同的错误,但是没有任何正确的答案.我希望这对其他人有用.

I know this is a bit shoddy and that is not the best way to code what I want to achieve. In spite of this, I've seen so many times the same error on the internet but without any correct answare. I wish this would be usefull for others.

有一个不错的代码!

这篇关于ListView getChildAt为不可见的元素提供NullPointer(Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆