使用overridePendingTransition导致列表适配器中的classcastexception

时间:2015-04-22 08:18:12

标签: android classcastexception listadapter

我使用适配器将数据加载到列表视图,并尝试将overridePendingTransitionintent一起使用。

这就是我使用它的方式,

((Activity) context).overridePendingTransition(
                        R.anim.slide_in_right, R.anim.slide_out_left);

这是adapter.java

public class CustomListAddress extends BaseAdapter {

    private Context context;
    private final List<String> firstName;


    public CustomListAddress(Context c, List<String> firstName) {

        this.context = c;
        this.firstName = firstName;

    }

    @Override
    public int getCount() {
        return firstName.size();
    }

    @Override
    public Object getItem(int position) {
        return firstName.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(context).inflate(
                    R.layout.address_list_item, parent, false);

            holder.tvHeader = (TextView) convertView.findViewById(R.id.lblname);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.tvHeader.setText(firstName.get(position));

        LinearLayout addresslist = (LinearLayout) convertView
                .findViewById(R.id.addressLayout);
        addresslist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent next = new Intent(context,
                        ActivityMyAddressAdd.class);
                next.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

                 next.putExtra("firstName", firstName.get(position));

                context.startActivity(next);
                ((Activity) context).overridePendingTransition(
                        R.anim.slide_in_right, R.anim.slide_out_left);
            }
        });

        return convertView;
    }

    private class ViewHolder {
        private TextView tvHeader;
    }
}

当我按照适配器类中所示尝试它时,它会崩溃并给出下面提到的异常。

enter image description here

2 个答案:

答案 0 :(得分:3)

您似乎正在将Application上下文而不是Activity上下文传递给CustomListAddress构造函数。为了开始新的Activity,您需要使用其上下文。

你应该做那样的事情:

public class SomeActivity extends Activity {
      CustomListAddress adapter;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
           ...
           adapter = new CustomListAddress(this, firstName);
           ...
      }
}

第一个参数SomeActivity.this应该诀窍

答案 1 :(得分:1)

我能够通过更改活动类中的这一行来实现答案,因为需要传递活动实例。

adapter = new CustomListAddress(ActivityMyAddressList.this,firstName)