Android中Toast内置的ImageView

时间:2013-03-06 20:16:06

标签: android android-layout alignment android-imageview toast

我正在为Android制作一个简单的Webview应用程序。当没有连接时,我正在显示一个覆盖所有屏幕的自定义Toast消息,但在Toast中我想显示ImageView的图像。问题是吐司覆盖了所有屏幕,因为我使用以下代码来执行此操作:

toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.FILL_VERTICAL, 0, 0);

我怎样才能将ImageView置于吐司中心?这是名为ImageView的吐司布局中的toast_custom_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:android1="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:orientation="horizontal"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/logo" 
        android:background="@color/white" />
</LinearLayout>

这是我的活动中的代码,它会在没有连接时显示吐司:

public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
    LayoutInflater inflater = getLayoutInflater();

    View layout = inflater.inflate(R.layout.toast_custom_layout,
            (ViewGroup) findViewById(R.id.toast_layout_root));

    Toast toast = new Toast(getApplicationContext());
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(layout);
    toast.show();
    toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.FILL_VERTICAL, 0, 0);
}

我非常感谢你的建议,朋友们。

2 个答案:

答案 0 :(得分:2)

尝试使用RelativeLayout代替

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:src="@drawable/logo" 
        android:background="@color/white" />

</RelativeLayout>

答案 1 :(得分:0)

尝试:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="horizontal"
android:padding="5dp" >

<ImageView
    android:id="@+id/imageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/logo" 
    android:background="@color/white"
    android:gravity="center" />
 </LinearLayout>

相关部分为android:gravity="center"