2015-07-21 210 views
0

我有一個嘗試創建自定義Toast對象的活動。我希望烤麪包出現在屏幕的中央,但無論我設定的重力是什麼,烤麪包都會出現在頂部。看起來我給敬酒的設置對發生的事情沒有影響。我能做些什麼來將敬酒移到中心。爲什麼SetGravity onToast沒有效果?

的代碼來創建敬酒:

LayoutInflater inflater = (LayoutInflater) context.getSystemService 
          (Context.LAYOUT_INFLATER_SERVICE); 
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.notification_layout,null); 

((TextView) layout.findViewById(R.id.title)).setText(title); 
((TextView) layout.findViewById(R.id.content)).setText(content); 
Toast toast = new Toast(this); 

toast.setDuration(Toast.LENGTH_SHORT); 
toast.setGravity(Gravity.CENTER, 0, 0); 
toast.setView(layout); 
toast.show(); 

的佈局膨脹的XML:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" android:layout_height="100dp" 
    android:id="@+id/notificationToast"> 

    <ImageView 
     android:layout_width="50dp" 
     android:layout_height="50dp" 
     android:src="@drawable/ic_launcher" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentStart="true" 
     android:id="@+id/imageView4" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceLarge" 
     android:text="Title" 
     android:id="@+id/title" 
     android:gravity="center" 
     android:layout_alignBottom="@+id/imageView4" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentEnd="true" 
     android:layout_toEndOf="@+id/imageView4" /> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="content" 
     android:id="@+id/content" 
     android:layout_below="@+id/imageView4" 
     android:layout_alignParentStart="true" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentEnd="true" /> 
</RelativeLayout> 

回答

2

你的麪包被充氣佈局的高度只有100dp。 CENTER變量將吐司放在其父級佈局的中心。將父佈局的高度設置爲整個屏幕(match_parent)。然後,當您調用setGravity(Gravity.CENTER,0,0)時,它將位於父佈局中心的屏幕中心。

吐司:http://developer.android.com/reference/android/widget/Toast.html 比重:http://developer.android.com/reference/android/view/Gravity.html

+0

愚蠢的小失誤總是最長的發現。謝謝 – nbroeking

+1

發生在我們身上 –

相關問題