我创建了一个包含项目列表的 ListView,每个项目都有自己的删除按钮。
我已经覆盖了 ArrayAdapter 中的 getView 方法,并将处理程序附加到删除按钮。
问题是,getView 方法被调用了两次。第二次,v.findViewById(DeleteButton) 调用返回 null。我检查了视图,并且 ImageButton 存在于层次结构中,但 Id 为 0。
谁能解释为什么会这样?
ManualFragment.java
public class ManualFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
View view = inflater
.inflate(R.layout.fragment_manual, container, false);
Button addButton = (Button) view.findViewById(R.id.AddButton);
ListView listView = (ListView) view.findViewById(R.id.ListView);
final List<String> items = new ArrayList<String>();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getActivity(), R.layout.list_item, R.id.TextItem, items) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ManualFragment.this.getLayoutInflater(savedInstanceState);
v = vi.inflate(R.layout.list_item, null);
}
TextView time = (TextView) v.findViewById(R.id.TextItem);
time.setText(items.get(position));
ImageButton delete = (ImageButton) v
.findViewById(R.id.DeleteButton);
//THIS LINE THROWS A NULLREF ON SECOND CALL
delete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ImageButton deleteButton = (ImageButton) v;
items.remove(deleteButton.getId());
notifyDataSetChanged();
}
});
delete.setId(position);
return v;
}
};
listView.setAdapter(adapter);
final EditText addText = (EditText) view.findViewById(R.id.AddText);
addButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String value = addText.getText().toString();
if (!"".equals(value)) {
items.add(value);
adapter.notifyDataSetChanged();
addText.setText("");
}
}
});
return view;
}
}
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:focusable="false" >
<TextView
android:id="@+id/TextItem"
android:layout_width="267dp"
android:layout_height="match_parent"
android:layout_weight="0.89"
android:focusable="false"
android:gravity="center_vertical"
android:text="Item"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageButton
android:id="@+id/DeleteButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:focusable="false"
android:src="@drawable/delete" />
</LinearLayout>
</LinearLayout>