简体   繁体   中英

Android ImageButton builds successfully but doesn't show

I am trying to create a simple app that when an ImageButton is clicked, a message is displayed on the screen. I am following along with this tutorial: http://www.mkyong.com/android/android-imagebutton-example/

EDIT: my entire XML files is as follows:

<LinearLayout 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"
android:orientation="horizontal">

<TextView
    android:textSize = "30sp"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:gravity = "center"
    android:text="@string/user_name" />
<ImageButton
    android:id="@+id/imageButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/me2" />
</LinearLayout>

and have the picture me2.png in my res/drawable-hdpi folder.

in my mainActivity.java file I have:

ImageButton imageButton;

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

    addListenerOnButton();

}

public void addListenerOnButton() {

    imageButton = (ImageButton) findViewById(R.id.imageButton1);

    imageButton.setOnClickListener(new Button.OnClickListener() {

        @Override
        public void onClick(View arg0) {

           Toast.makeText(MainActivity.this,
            "ImageButton is clicked!", Toast.LENGTH_SHORT).show();

        }

    });

}

However, when I run my app on my device (not emulator) all it does is display a string of my name that I had already implemented leaving the rest of the page/layout blank.

Any thoughts? Everything builds successfully. Thanks!

The problem is that your orientation is horizontal:

android:orientation="horizontal"

but your TextView takes up whole space:

android:layout_width="fill_parent"

As a result, your ImageView is placed "right" of the device screen. Switch your orientation to vertical:

android:orientation="vertical"

and you'll see it. Cheers!

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