我對自定義列表項目(包括按鈕)使用ListView。我有一個自定義的適配器,其中我將按鈕的OnClickListener設置爲內部類(在適配器類中定義)。從另一個佈局訪問視圖
我想訪問在其中顯示列表視圖的類中的按鈕(定義在ListAcitivty類的不同xml文件中)。我想在這個類中設置onClickListener方法。要做到這一點,最好的方法是什麼?
編輯: 這是我的list_item.xml(我用於我的ListView行)。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/imageView"
android:layout_width="22dp"
android:layout_height="wrap_content"
android:layout_marginLeft="4dp"
android:layout_marginRight="10dp"
android:layout_marginTop="4dp"
android:contentDescription="Color"
android:src="@drawable/ic_launcher" >
</ImageView>
<EditText
android:id="@+id/nameEdit"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:textSize="20dp"
android:inputType="textPersonName"
>
</EditText>
<Button
android:id="@+id/deleleButton"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="@drawable/delete_button" >
</Button>
</LinearLayout>
如何在擴展ListActivity的類中訪問按鈕(id:deleteButton)?擴展listactivity的類有一個單獨的佈局(main.xml讓我們說)。如果我在擴展listactivity的類內部執行setContentView(main),findViewById(R.id.deleteButton)將返回null。
編輯2: 這是我的類擴展ListActivity。如果我將findViewById(R.id.deleteButton)放在setContentView之後,它將返回null。
public class PlayerSelection extends ListActivity {
ListView list;
ArrayList<PlayerField> textviews = null;
PlayerFieldsAdapter adapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_selection_page);
list = getListView();
textviews = new ArrayList<PlayerField>();
for (int i = 0; i< GlobalVariables.getPlayers(); i++) {
textviews.add(i, new PlayerField());
}
adapter = new PlayerFieldsAdapter(this, R.layout.list_item, textviews);
ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.list_header, null);
Button backButton = null;
for (int i = 0; i < header.getChildCount(); i++) {
View v = header.getChildAt(i);
if (v instanceof Button) {
backButton = (Button) v;
break;
}
}
backButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent optionsIntent = new Intent(PlayerSelection.this, OptionsScreen.class);
startActivity(optionsIntent);
}
});
list.addHeaderView(header);
list.setAdapter(adapter);
}
你應該考慮發佈一些代碼,因爲很難理解這個問題。 – Egor 2012-07-08 08:58:09
我添加了代碼,希望現在更清楚。 – user1478754 2012-07-08 09:19:34
我的意思是Java代碼,而不是XML – Egor 2012-07-08 09:21:02