从另一个onClick方法控件获取对ListView控件的访问权



我如何获得访问,例如,TextView,从onClick方法分配给,例如,ImageView?TextView和ImageView组成ListView项。

在我的item.xml中我有:

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
> 
<ImageView
    android:id="@+id/img"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:onClick="onImgClick"
    />      
<TextView android:id="@+id/text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

在我的ListActivity中我有onImgClick方法

 public void onImgClick(View v) {
    TextView tv = (TextView) v.findViewById(R.id.text);
tv.setText("Hello world!");
} 

但是视图v -这是ImageView,所以在这个方法中我有致命异常:

java.lang.NullPointerException

on line:

tv.setText("Hello world!");

我知道这不是正确的方式来获得访问TextView。我知道我可以使用onlisttitemclick (ListView l, View v, int position, long id)根据整个ListView。但是我想通过ImageView的onClick方法来实现这个

我的问题解决了。我只需要在我的LinearLayout上设置id:

android:id="@+id/main_layout"

然后像这样做:

public void onImgClick(View v) {
    LinearLayout linearLayout = (LinearLayout) v.getParent();       
    TextView textView = (TextView) linearLayout.findViewById(R.id.text);        
    textView.setText("Hello world!");
}

访问TextView的最简单方法是通过Handler并使用sendMessage:

http://developer.android.com/reference/android/os/Handler.html

或者,根据您如何实现它,您可能希望查看getParent(),如v.getParent().findViewById(r.id.text);

我不确定这是否适用于你的情况。

在listview的getView方法中设置onclick侦听器的listview

我建议您重写ListAdapter,并在getView()中将侦听器设置为父视图。使用setTag()使识别更容易。

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
...
getView (int position, View convertView, ViewGroup parent){
 LinearLayout thisview = null;
 if(convertView == null){
  convertView = inflater.inflate(R.layout.item, parent);
 }
 TextView tv = convertView.findViewById(R.id.text);
 ImageView img = convertView.findViewById(R.id.img);
 img.setTag("uniqueid_"+position);
 //this will put a reference to the TextView in the ImageView
 img.setKey("TEXT_VIEW", tv);
 img.setOnClickListener(this);
 ...
 return convertView;
}

你可以得到TextView与v.getKey("TEXT_VIEW")在onClick()…但这似乎是一个很好的潜在内存泄漏。

最新更新