我正在尝试编写一个 ListView 适配器,它将基于几个 xml 文件之一传递一个视图,具体取决于我为其创建视图的数据的属性。我的代码工作正常,除非我尝试使用 convertView 来加快进程。无论我如何尝试使用它,我要么崩溃我的程序,要么得到奇怪的输出。我理解为什么这对 convertView 来说是个问题,但我强烈怀疑我仍然可以完成这项工作。谁能告诉我如何修复我的代码?(现在我使用 convertView 作为我返回的视图的名称,即使我没有 'if (convertView==null)' 例程正常工作)
public class PaymentListFragment extends ListFragment {
private ArrayList<Payment> mPayments;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setTitle(R.string.payment_schedule_title);
mPayments = PaymentSchedule.get(getActivity()).getPayments();
PaymentAdapter adapter = new PaymentAdapter(mPayments);
setListAdapter(adapter);
}
private class PaymentAdapter extends ArrayAdapter<Payment> {
public PaymentAdapter(ArrayList<Payment> payments) {
super(getActivity(), 0, payments);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Payment p = mPayments.get(position);
//normal
//if (convertView == null) {
//cant work out how to use convertview conditional without screwing up project
//it would speed it up to fix this however
if (p.type == Payment.TYPE_START) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_start, null);
TextView remainDisplay =
(TextView) convertView.findViewById(R.id.remainDisplayStart);
remainDisplay.setText(p.getRemainString());
TextView paymentDate =
(TextView) convertView.findViewById(R.id.paymentDateStart);
paymentDate.setText(p.getDateString());
TextView paymentDisplay =
(TextView) convertView.findViewById(R.id.paymentDisplayStart);
paymentDisplay.setText(p.getDefaultPaymentString());
TextView aprDisplay =
(TextView) convertView.findViewById(R.id.aprDisplayStart);
aprDisplay.setText(p.getInterestRate() * 1200 + "%");
} else {
//if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item_payment, null);
//}
TextView paymentDate =
(TextView) convertView.findViewById(R.id.paymentDate);
paymentDate.setText(p.getDateString());
TextView paymentDisplay =
(TextView) convertView.findViewById(R.id.paymentDisplay);
paymentDisplay.setText(p.getPaymentString());
TextView principalDisplay =
(TextView) convertView.findViewById(R.id.principalDisplay);
principalDisplay.setText(p.getPrincipalString());
TextView interestDisplay =
(TextView) convertView.findViewById(R.id.interestDisplay);
interestDisplay.setText(p.getInterestString());
TextView remainDisplay =
(TextView) convertView.findViewById(R.id.remainDisplay);
remainDisplay.setText(p.getRemainString());
}
//}
return convertView;
}
}
}