使用我写的这个类:
public class TopToast
{
private TextView m_tv = null;
private Toast m_Toast = null;
private Activity m_Activity = null;
public TopToast(Activity activity)
{
m_Activity = activity;
m_Toast = new Toast(m_Activity);
}
public void show(String text, int TextColor)
{
LayoutInflater inflater = m_Activity.getLayoutInflater();
View layout = inflater.inflate(R.layout.popup, null);
m_tv = (TextView)layout.findViewById(R.id.popup);
m_tv.setTextColor(ContextCompat.getColor(m_Activity, TextColor));
m_tv.setText(text);
final TypedArray styledAttributes = m_Activity.getTheme().obtainStyledAttributes(new int[] { android.R.attr.actionBarSize });
int Y = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
m_Toast.setGravity(Gravity.TOP | Gravity.START | Gravity.FILL_HORIZONTAL, 0, Y);
m_Toast.setDuration(Toast.LENGTH_LONG);
m_Toast.setView(layout);
m_Toast.show();
}
// Call this if you wish to hide toast quickly (viz. from onPause of activity, so that if user closes activity quickly toast too will disappear)
public void hide()
{
if (m_Toast!=null)
m_Toast.cancel();
if (m_tv!=null)
m_tv.setVisibility(View.GONE);
}
}
和xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content">
<TextView
android:id="@+id/popup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textColor="@color/red"
android:background="@color/white"
android:textAppearance="?android:attr/textAppearanceSmallPopupMenu"/>
</LinearLayout>