krrish
krrish

Reputation: 343

Using ImageButton in Android Eclipse IDE

I'm trying to use the ImageButton in Eclipse IDE (ADT).

The IDE shows no errors at the time of compiling but when I run it in emulator it never starts instead it shows like UNFORTUNATELY YOUR APP HAS STOPPED WORKING.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:contentDescription="@string/app_name"
    android:src="@drawable/ic_launcher" />

AND main.activity.java

public class MainActivity extends Activity {


Button button1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addListenerOnButton();
    }

    public void addListenerOnButton() {

        final Context context = this;

        button1 = (Button) findViewById(R.id.imageView1);

        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent(context, ImageActivity.class);
                startActivity(intent);   

            }

        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

Upvotes: 0

Views: 1481

Answers (2)

MSr
MSr

Reputation: 288

 button1 = (Button) findViewById(R.id.imageView1);

Change Button to ImageView And in the xml add this line to your image view

android:clickable="true"

Upvotes: 2

clemp6r
clemp6r

Reputation: 3723

That is because you cast an ImageView to a Button, which is incorrect.

Your variable button1 must be of type ImageView.

You can also use the ImageButton type, but be sure to use compatible types in the XML layout and in your Java code.

Upvotes: 0

Related Questions