我创建了一个ListView,其中包含一个项目列表,每个项目都有自己的删除按钮。
我已经覆盖了ArrayAdapter中的getView方法,并将处理程序附加到了delete按钮。
问题是,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>
答案 0 :(得分:0)
您正在使用
进行设置delete.setId(position)
我认为你想用位置标记buttojn
delete.setTag(position)