[英]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"
結果,您的ImageView放置在設備屏幕的“右側”。 將方向切換為垂直:
android:orientation="vertical"
然后您會看到它。 干杯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.