【发布时间】:2023-03-29 21:11:02
【问题描述】:
我一直在尝试获取自定义 toast 的高度,以便可以使用以下代码在按钮的右上角显示 toast:
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class MyToast {
public static void showToast(Context context, View v, String s) {
int pos[] = new int[2];
v.getLocationOnScreen(pos);
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View layout = inflater.inflate(R.layout.toast_style, (ViewGroup) v.findViewById(R.id.toast_layout_root));
TextView text = (TextView) layout.findViewById(R.id.toast_text);
text.setText(s);
Toast toast = new Toast(context);
toast.setGravity(Gravity.TOP|Gravity.LEFT, pos[0] + v.getWidth(), pos[1] - v.getHeight());
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
}
我通过了按钮的视图,所以我可以得到我想要放置吐司的位置,但是 v.getHeight() 不是完成这项任务所需的高度,有什么建议吗?
这是xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="8dp"
android:background="@drawable/frame_outline" >
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textStyle="italic"
android:textSize="12sp"
android:typeface="serif"
android:gravity="center"
android:textColor="@color/holo_text" />
</LinearLayout>
【问题讨论】:
-
我尝试使用 text.getHeight() 和 layout.getHeight() 但两者都为零
-
方法何时被调用?也许视图还没有绘制?
-
我不能检索正在创建的视图的高度吗?它不应该显示有高度
-
@Raddy 发布您的 xml
-
即使自从我上次使用 Android 开发以来已经过去了很多时间,我确信 Android 不会向您报告 View 的高度/宽度,直到它没有绘制它。如果没有显示,Android 不会绘制视图,因为没用。
标签: android android-toast