我通过SO搜索了很多,有几个主题正在谈论这个问题。但实际上没有人帮忙,我已经用数据填充了适配器,现在我想删除每行中带有专用按钮的行,其中一个线程有一个建议:写一个onClickListener
in适配器的getView()
方法。当我尝试这样做时,出现了IndexOutOfBound
异常。更准确地说,当我单击第一行上的删除按钮时,没有任何反应,但在第二行和最后一行中单击删除按钮会出现异常
这是我试图做的事情,Android工作室建议职位变量应该是最终的:
public class TimeTrackerAdapter extends BaseAdapter {
public ArrayList<TimeRecord> times=new ArrayList<TimeRecord>();
@Override
public int getCount() {
return times.size();
}
public TimeTrackerAdapter()
{
times.add(new TimeRecord("12:30","this is the best"));
times.add(new TimeRecord("2:30","I need this"));
}
@Override
public Object getItem(int position) {
return times.get(position);
}
public void addTimeRecord(TimeRecord timeRecord)
{
times.add(timeRecord);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View view, ViewGroup parent) {
if(view==null) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.inflate(R.layout.menu_layout, parent, false);
}
Button button=(Button) view.findViewById(R.id.delete_entry);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
times.remove(position);
}
});
TextView timeView=(TextView) view.findViewById(R.id.time_textView);
TextView noteView=(TextView) view.findViewById(R.id.note_TextView);
TimeRecord time=times.get(position);
timeView.setText(time.getTime());
noteView.setText(time.getNote());
return view;
}
}
这里是错误堆栈:
08-21 10:47:20.330 20400-20400/com.example.sam.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.sam.myapplication, PID: 20400
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.remove(ArrayList.java:403)
at com.example.sam.myapplication.TimeTrackerAdapter$1.onClick(TimeTrackerAdapter.java:55)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:2)
您需要在按钮onClick方法
中添加notifyDataSetChanged() Button button=(Button) view.findViewById(R.id.delete_entry);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
times.remove(position);
notifyDataSetChanged();
}
});
答案 1 :(得分:1)
每当添加/删除项目时都应该调用notifyDataSetChanged。这里的片段
$scope.getCount = function(field, value){
var obj = {};
obj[field] = value;
return _.where($scope.players, obj).length;
};