繁体   English   中英

Android ImageButton成功构建但未显示

[英]Android ImageButton builds successfully but doesn't show

我试图创建一个简单的应用程序,当单击ImageButton时,屏幕上会显示一条消息。 我将跟随本教程: http : //www.mkyong.com/android/android-imagebutton-example/

编辑:我的整个XML文件如下:

<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>

并将图片me2.png放在我的res / drawable-hdpi文件夹中。

在我的mainActivity.java文件中,我有:

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();

        }

    });

}

但是,当我在设备(而非仿真器)上运行应用程序时,它所做的只是显示一个我已经实现的名称字符串,其余页面/布局保留为空白。

有什么想法吗? 一切都成功构建。 谢谢!

问题是您的方向是水平的:

android:orientation="horizontal"

但是您的TextView会占用整个空间:

android:layout_width="fill_parent"

结果,您的I​​mageView放置在设备屏幕的“右侧”。 将方向切换为垂直:

android:orientation="vertical"

然后您会看到它。 干杯!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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