如何在ListView适配器中获取list_view_item.xml的根视图?

时间:2012-12-19 10:12:41

标签: android android-layout

我有一个ListView项目/单元格,它有几个层,relative,linearLayout等。 我尝试在按钮的onClick中执行v.getParent(),但它只是向上一层。如何在onClick事件处理程序中获取对当前元素的根的引用?

这是我的getView()

             Button v = (Button)findViewById(R.id.myButton);

             v.setOnClickListener(new OnClickListener(){
                     onClick(View v) {

                        //Right here I want to find another view inside the cell.
                        View otherView = ???.findViewById(R.id.myOtherViewInListItem); 
                             otherView.setBackgroundColor(...);
                        .........................................
                     } 
              });

2 个答案:

答案 0 :(得分:0)

我想象这个按钮在ListView元素中。基于这个假设:

  1. 只创建一个OnClickListener。你正在做的事情就是创建adapter.getCount() OnClick监听器并浪费内存。

  2. 也许您想要完全删除按钮并使用OnItemClick跟踪整个ListView元素的点击次数,这将向您传递对整个视图的引用。

  3. 如果你真的必须有这个按钮,你可以在你的getView中存储一个对父类的引用,如下所示:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // do whatever you're doing to get the view, let's call it v
        Button b = (Button)v.findViewById(/* your button id */ )
        b.setTag(v)
    }
    
  4. 然后在您的点击监听器上,您可以:

        onClic(View v){
            View parent = (View)b.getTag();
        }
    

    如果那个答案适合你(我知道它确实如此),就像Daniel Martinus指出的那样接受它是正确的。

答案 1 :(得分:0)

 Inside onClick(View v)

just call v.getViewParent();  then you will have a view from which you can call the find for   the others.