android 自定義Toast增加點選事件、Toast彈出隱藏動畫、Toast寬度為match_parent
阿新 • • 發佈:2019-02-15
在自定義Toast的時候,可能會用到點選事件,但是android系統本身Toast只是用於提示,並不支援點選事件,即使自定義Toast也不支援點選事件,檢視Toast原始碼可以發現,其內部的TN.class(該為私有類,外部調用不了)裡面的WindowManager.LayoutParams 的flags屬性有WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
,如圖:
所以,要想Toast開啟點選事件,需要通過反射的方法來改變其內部的WindowManager.LayoutParams的flags,去掉WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
實現如下:
public class ClickToast{
private static Toast mToast;
private static Button btn;
public static void showToast (final Context context, int duration){
if(mToast == null){
LayoutInflater inflater = (LayoutInflater)context.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//自定義佈局
View view = inflater.inflate(R.layout.toast_mytoast, null);
btn= view.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//這裡可以做點選操作
}
});
mToast = Toast.makeText(context.getApplicationContext(), "" , duration);
//這裡可以指定顯示位置
// mToast.setGravity(Gravity.BOTTOM, 0, 0);
mToast.setView(view);
}
try {
Object mTN ;
mTN = getField(mToast, "mTN");
if (mTN != null) {
Object mParams = getField(mTN, "mParams");
if (mParams != null
&& mParams instanceof WindowManager.LayoutParams) {
WindowManager.LayoutParams params = (WindowManager.LayoutParams) mParams;
//顯示與隱藏動畫
params.windowAnimations = R.style.ClickToast;
//Toast可點選
params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//設定viewgroup寬高
params.width = WindowManager.LayoutParams.MATCH_PARENT; //設定Toast寬度為螢幕寬度
params.height = WindowManager.LayoutParams.WRAP_CONTENT; //設定高度
}
}
} catch (Exception e) {
e.printStackTrace();
}
mToast.show();
}
/**
* 反射欄位
* @param object 要反射的物件
* @param fieldName 要反射的欄位名稱
*/
private static Object getField(Object object, String fieldName)
throws NoSuchFieldException, IllegalAccessException {
Field field = object.getClass().getDeclaredField(fieldName);
if (field != null) {
field.setAccessible(true);
return field.get(object);
}
return null;
}
}
使用:
ClickToast.showToast(MainActivity.this, Toast.LENGTH_LONG);
動畫:
style.xml
<style name="ClickToast" parent="@android:style/Animation.Toast">
<item name="android:windowEnterAnimation">@anim/anim_clicktoast_in</item>
<item name="android:windowExitAnimation">@anim/anim_clicktoast_out</item>
</style>
anim_clicktoast_in.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 進入動畫 -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromYDelta="100"
android:toYDelta="0"
android:duration="200"
/>
</set>
anim_clicktoast_out.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- 出去動畫 -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromYDelta="0"
android:toYDelta="100"
android:duration="200"
/>
</set>