我正在尝试将片段和列表视图与数组适配器一起使用,并且无法从数组适配器中的 onClickListener 调用我的方法。
如果我正确理解模式,片段应该是自给自足的,所以我想把我的业务逻辑放在那里。但我无法从阵列适配器调用它。如果我把它放在主要活动中,我可以调用它,但这不妨碍我在另一个活动中使用片段并打破范式吗?
我的业务逻辑是在错误的地方,还是我没有正确调用它?
这是我的 ArrayAdapter;
public class RecipientsListAdapter extends ArrayAdapter<Recipient>{
Context context;
int layoutResourceId;
Recipient data[] = null;
public RecipientsListAdapter(Context context, int layoutResourceId, Recipient[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
RecipientHolder holder = null;
final boolean isLastRow = (position == data.length-1);
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecipientHolder();
holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (RecipientHolder)row.getTag();
}
final Recipient recipient = data[position];
holder.txtTitle.setText(recipient.displayName);
holder.imgIcon.setImageResource(recipient.icon);
row.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity)context).onChildItemSelected(position);
if(isLastRow){
//((RecipientsFragment).getContext()).launchContactPicker();
((MainActivity)context)).launchContactPicker();
}
else{
Toast.makeText(getContext(), recipient.displayName, Toast.LENGTH_SHORT).show();
}
}
});
return row;
}