创建自定义SimpleCursorAdapter

时间:2011-12-10 12:49:28

标签: android simplecursoradapter

我创建了一个自定义的SimpleCursorAdapter,因为我想要一个文本和每行2个按钮。

如果我点击一个按钮,他应该调用Activity Lektion。 在这个Lektion中,他应该知道调用来自哪个Button,所以我想在onClickEvent中将Lektion的id作为Bundle发送。

但这不起作用,它只是让我永远保存最后一个ID ..

我该怎么做?

public class LektionenCursorAdapter extends SimpleCursorAdapter{
    private Cursor c;
    private Context context;
    private Bundle bundle;

    public LektionenCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
        this.c = c;
        this.context = context;
    }


    public View getView(int pos, View inView, ViewGroup parent){
       if(inView == null){
           inView = View.inflate(context, R.layout.lektionenoverview_entry, null);
       }
       View row = inView;

       this.c.moveToPosition(pos);

       String id = this.c.getString(this.c.getColumnIndex("_id"));
       Log.i("Cursor", id);
       String description = this.c.getString(this.c.getColumnIndex("Description"));
       String info = this.c.getString(this.c.getColumnIndex("Info"));
       String test = this.c.getString(this.c.getColumnIndex("Test"));

       TextView descriptionTextView = (TextView)row.findViewById(R.id.description);
       Button infoButton = (Button)row.findViewById(R.id.infoButton);
       Button testButton = (Button)row.findViewById(R.id.testButton);

       bundle = new Bundle();
       bundle.putString("LektionNummer", id);

       descriptionTextView.setText(id+". "+description);

       if(info != null && info.length() > 0){          
            infoButton.setOnClickListener(new OnClickListener() {           
            public void onClick(View v) {
                Intent intent = new Intent(context, Lektion.class);
                intent.putExtras(bundle);
                context.startActivity(intent);                  
            }
        });

       }
       if(test != null && test.length() > 0){

       }
       return row;
    }

}

1 个答案:

答案 0 :(得分:0)

不需要使用CursorAdapter,因为你想显示2行和按钮,你可以使用任何其他更简单的适配器。

每个视图都会多次调用getView方法,而不是在单击视图或按钮时。您每次都要重新实例化Bundle,它只是保存最后一次getView调用的id(因为每次调用都会破坏前一个调用),并且您还在每次调用时创建一个新的OnClickListener。

您可能希望使用OnItemClickListener并在getView()方法之外只创建一个实例。