我試圖用陣列適配器使用片段和列表視圖,並且無法從陣列適配器中的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;
}