How to start an activity by click of image button of a List view?

自古美人都是妖i 提交于 2019-12-02 05:59:12

问题


i have a list there is a image button in each item when i click on a image i have to start another Activity with intent

following are my code

my problem is i couldn't call startActivity() from custom adapter! !

in custom adapter's getView()

  holder.profilePicture.setOnClickListener(new OnClickListener() 
       { 
           public void onClick(View v) 
           {
               Log.d("OnImageButton","Clicked");
               Intent zoom=new Intent(AllProfile.getAppContext(), ImageZoom.class);
               int imageID=holder.profilePicture.getId();
               zoom.putExtra("ImageId", imageID);
               startActivity(zoom)  ; //This line raises error !      
                           }


       });

回答1:


You should pass your context to your custom adapter when you create it:

public class MyAdapter extends BaseAdapter {
    private Context mContext;

    public MyAdapter (Context ctx) {
        mContext = ctx;
    }

    ...
}

And in getView use that context to start the Activity:

 holder.profilePicture.setOnClickListener(new OnClickListener() 
   { 
       public void onClick(View v) 
       {
           Log.d("OnImageButton","Clicked");
           Intent zoom=new Intent(mContext, ImageZoom.class);
           int imageID=holder.profilePicture.getId();
           zoom.putExtra("ImageId", imageID);
           mContext.startActivity(zoom)  ; //This line raises error !      
                       }


   });

When you create the Adapter in your Activity you should pass "this" as a parameter:

 mAdapter = new MyAdapter(this);



回答2:


have you tried this:

MainActivity.this.startActivity(zoom);


来源:https://stackoverflow.com/questions/17190268/how-to-start-an-activity-by-click-of-image-button-of-a-list-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!