[英]Unable to capture the button click in a listview ? Please tell me why this code doesn't work
我的主要活動中有一個列表視圖,其后是一個文本視圖。 列表視圖中包含按鈕。 當單擊列表中的按鈕時,我希望一些文本出現在textatrea上。 但是我無法捕獲按鈕的單擊。
以下是我使用的代碼。 請告訴我有什么問題。 (我不需要替代解決方案,但我想知道代碼中的錯誤)
public class MyFirstAppActivity extends Activity implements OnItemClickListener {
ListView listview ;
String[] array = new String[] {"Click1","Click2"};
ArrayAdapter <String> arrayadapter;
TextView textview;
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.main);
arrayadapter = new ArrayAdapter<String>(this, R.layout.button,array);
listview = (ListView)findViewById(R.id.lv_1);
listview.setAdapter(arrayadapter);
listview.setOnItemClickListener(this);
}
public void onItemClick(AdapterView<?>arg1,View v,int Position, long id){
textview = (TextView)findViewById(R.id.textview);
textview.setText("Hello, you just clicked a button"+Position);
}
}
如下所示,將活動設置為main.xml。 但是,當我單擊列表中的按鈕時,未捕獲到單擊。 為什么會這樣呢?
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ListView android:id="@+id/lv_1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<TextView android:id = "@+id/textview"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_below = "@id/lv_1"
android:text="Message about the button is displayed here">
</TextView>"
</RelativeLayout>
button.xml
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/button" >
</Button>
您是在說一件事而在編碼另一件事...
onItemClick
處理單擊列表行而非按鈕的行為。
在這種情況下,該按鈕正在竊取該行中的單擊,因此不會調用您的onItemClick。
有兩種方法可以解決此問題,具體取決於您真正想要發生的事情。
如果確實要單擊按鈕本身而不是單擊行,則需要覆蓋適配器的getView
方法,並為按鈕放入OnClickListener
。
如果您只是單擊該行而感到高興(這看起來就像單擊按鈕,因為那是該行中唯一的事情),則需要阻止該按鈕竊取列表行中的點擊。 您可以通過在xml中的按鈕上設置android:focusable="false"
和android:focusableInTouchMode="false"
來實現。
完成此操作后,您將擁有NPE ...
您的行布局中沒有R.id.textview
,因此onItemClick
將引發NPE,因為findViewById
將返回null,然后setText失敗。 您需要從單擊的行導航到父布局,然后找到textview(如果您也從getView
方法執行此操作,則幾乎相同...
假設您堅持使用OnItemClick
方法:
public void onItemClick(AdapterView<?>arg1,View v,int Position, long id){
ListView lv = (ListView) v.getParent();
RelativeLayout rl = (RelativeLayout) lv.getParent();
textview = (TextView) rl.findViewById(R.id.textview);
textview.setText("Hello, you just clicked a button"+Position);
}
將此代碼android:descendantFocusability="blocksDescendants"
放入listview子xml中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.