我一直在尝试获取自定义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();
}
}
我传递了按钮的视图,以便获取我想要放置toast的位置,但是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>