简体   繁体   中英

Why I am not able to change layout with button in a ListView?

I am not able to change layout when clicking on the button. Actually, I always use this code:

@Override
    public void onClick(View view) {
        if (view == imageButtonOrders) {
            startActivity(new Intent(this, Order.class)); }

Now, I want to use this function in my ListView . But when I use it I am getting an error. How can I fix it?

SwipeListAdapterP.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.product_items, null);

    TextView pk = (TextView) convertView.findViewById(R.id.pk);
    TextView name = (TextView) convertView.findViewById(R.id.name);
    TextView point = (TextView) convertView.findViewById(R.id.point);
    ImageButton imageButtonDelete = (ImageButton) convertView.findViewById(R.id.imageButtonDelete);
    ImageButton imageButtonUpdate = (ImageButton) convertView.findViewById(R.id.imageButtonUpdate);

    ProductItems m = productList.get(position);

    pk.setText(String.valueOf(m.getPk()));
    name.setText(String.valueOf(m.getName()));
    point.setText(String.valueOf(m.getPoint()));

    imageButtonDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(this, Order.class));
    }});

You need your parent activity context to start Activity from your Adapter class.

instead of:

 startActivity(new Intent(this, Order.class));

use:

 activity.startActivity(new Intent(activity, Order.class));

where activity is the Activity context your are passing to your Adapter class

try OnClick this way

//cast imageButtonOrders by findViewById()

@Override
    public void onClick(View view) {
        if (view.getId() == imageButtonOrders) {
            startActivity(new Intent(this, Order.class));
     }

in Adapter You need to Initialize Context with Activity reference and pass that Context on Intent

imageButtonDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(`Context`, Order.class));
    }});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM