I want to control a toast's show and hide action, so I use reflect to get show and hide method through variable mTN, but the toast not show when I call showMethod, that's the code:
-
Creation of toast:
final TextView tView = new TextView(MainActivity.this); tView.setText("ReflectToast !!!"); tView.setBackgroundColor(getResources().getColor(R.color.float_window_color2)); toast = new ReflectToast(MainActivity.this, tView);
-
calling of show method:
mFloatBtn = findViewById(R.id.startFloatWindow); mFloatBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(isShown){ toast.cancel(); isShown = false; }else{ toast.show(); isShown = true; } } });
-
Definition of Toast class: class ReflectToast {
Context mContext; private Toast mToast; private Field field; private Object obj; private Method showMethod, hideMethod; public ReflectToast(Context c, View v) { this.mContext = c; mToast = new Toast(mContext); mToast.setView(v); reflectionTN(); } public void show() { try { Log.v("toast", "show enter"); showMethod.invoke(obj, new Object[]{}); } catch (Exception e) { e.printStackTrace(); } } public void cancel() { try { hideMethod.invoke(obj, new Object[]{}); } catch (Exception e) { e.printStackTrace(); } } private void reflectionTN() { try { field = mToast.getClass().getDeclaredField("mTN"); field.setAccessible(true); obj = field.get(mToast); showMethod = obj.getClass().getDeclaredMethod("show", new Class[ 0 ]); hideMethod = obj.getClass().getDeclaredMethod("hide", new Class[ 0 ]); } catch (Exception e) { e.printStackTrace(); } }
}
Aucun commentaire:
Enregistrer un commentaire