2014-01-08 33 views
0

我有这个实现ListAdapter的:访问对象点击

public class TaskAdapter implements ListAdapter, View.OnClickListener { 

Context     context; 

List<Task>    tasks; 

// View adapterView; 
public TaskAdapter(Context context, List<Task> tasks) { 
    super(); 
    this.context = context; 
    this.tasks = tasks; 
} ... 

@Override 
public View getView(int position, View convertView, ViewGroup parent) 
{ 
    Task data = tasks.get(position); 
    Button task_menu_bt = (Button)root.findViewById(R.id.taskMenuButton); 

     task_menu_bt.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 
       **//  How to access current Task data?? i can not do tasks.get(position)** 
      } 
     }); 

}

我的问题是如何从onClick事件中访问坐落在一个按钮任务数据项目行(不是视图点击,而是列表视图上的按钮)?

我的任务类包含〔实施例的getName()方法和其他...

+0

你应该看看[OnItemClickListener](http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html)。 – tolgap

+0

为什么不能在那里使用'task.get(position)'? – tyczj

+0

@tyczj“不能引用在一个不同的方法中定义的内部类中的非最终变量数据” –

回答

0

由于您使用onClickListener的作为一个内部类来实现,变量将不可访问它。 所以您应该在适配器级别声明一个任务变量,TaskAdapter的基本成员或使其最终无论是否会工作

public class TaskAdapter implements ListAdapter, View.OnClickListener { 

Context     context; 

List<Task>    tasks; 
Task data; 

// View adapterView; 
public TaskAdapter(Context context, List<Task> tasks) { 
    super(); 
    this.context = context; 
    this.tasks = tasks; 
} ... 



@Override 
public View getView(int position, View convertView, ViewGroup parent) 
{ 
    data = tasks.get(position); 
    Button task_menu_bt = (Button)root.findViewById(R.id.taskMenuButton); 

     task_menu_bt.setOnClickListener(new View.OnClickListener() 
     { 
      @Override 
      public void onClick(View v) 
      { 
       **//  How to access current Task data?? i can not do tasks.get(position)** 
      } 
     }); 

final Task data = tasks.get(position); 

其中一个更好的方式来访问项目覆盖getItem方法从那里返回数据源中的对象。

public Object getItem (int position){ 
    return (Task)tasks.get(position); 
} 
0

您应该能够通过更改任务的实例来访问数据

final Task data = tasks.get(position);