我需要以编程方式创建一个使用 ImageView 和 TextView 的 Toast,它出现在屏幕中间,我已经完成了。
这是我想要的渲染
(带心的黑色方块是ImageView图像,“J'aime”是TextView)
XML 代码:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ImageView
android:id="@+id/toastImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="1dp"
android:src="@drawable/like" />
<TextView
android:id="@+id/toastText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="85dp"
android:text="J'aime !"
android:textColor="#FFFFFF" />
</FrameLayout>
这是我使用 JAVA 代码的渲染:
JAVA代码:
FrameLayout toastLayout = new FrameLayout(this);
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
toastLayout.setLayoutParams(llp);
ImageView toastImg = new ImageView(this);
Bitmap toastBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.like);
toastImg.setImageBitmap(toastBitmap);
TextView toastText = new TextView(this);
toastText.setText("J'aime !");
LinearLayout.LayoutParams toastTextLp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
toastTextLp.setMargins(0, 85, 0, 0);
toastText.setLayoutParams(toastTextLp);
toastLayout.addView(toastImg);
toastLayout.addView(toastText);
Toast toast = new Toast(this);
toast.setView(toastLayout);
我尝试过使用相对布局或线性布局,但框架布局对此效果更好。所以我有一个问题:
什么是 JAVA 等价物:
android:layout_gravity="center_horizontal"
android:layout_marginTop="85dp"
? 因为这显然不是:
LinearLayout.LayoutParams toastTextLp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
toastTextLp.setMargins(0, 85, 0, 0);
需要帮忙。