roiberg
roiberg

Reputation: 13747

How to make an imagebutton clickable?

I want to make an ad banner.
Right now i have an imagebutton that displays an image from the web. The thing is that I cant make it clickable.

where should I put the onclick method?

Code I have tried so far:

public class ProjectActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    BannerActivity ba = new BannerActivity(this);

    LinearLayout layout = (LinearLayout)findViewById(R.id.main_layout);
    layout.addView(ba);
}

and thats my banner:

public class BannerActivity extends ImageButton{
    public BannerActivity(Context context) {
        super(context);
        setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 300));

        URL url = null;
        try {
            url = new URL("http://3.bp.blogspot.com/_9UYLMDqrnnE/S4UgSrTt8LI/AAAAAAAADxI/drlWsmQ8HW0/s400/sachin_tendulkar_double_century.jpg");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        InputStream content = null;
        try {
            content = (InputStream)url.getContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Drawable d = Drawable.createFromStream(content , "src"); 
        setBackgroundDrawable(d);
    }
}
}

as you can understand, the BannerActivity class is the banner and the project will add it as a jar file.

I dont want to put the onclick method in the "project" class, it should be somewhere in the BannerActivity that the developer will need to add to his project. Thanks!

Upvotes: 0

Views: 310

Answers (2)

nhaarman
nhaarman

Reputation: 100438

public class BannerActivity extends ImageButton implements OnClickListener{
    public void BannerActivity(Context context){
        super(context)

        //(...)

        setOnClickListener(this);
    }

    @Override
    public void onClick(View v){
        //Do your stuff.
    }
}

Upvotes: 1

Mohamed_AbdAllah
Mohamed_AbdAllah

Reputation: 5322

You need to Override the onClick() Method inside the BannerActivity to perform your desired action.

Upvotes: 1

Related Questions