这是一个有点奇怪的问题,而且很简单,但我被困住了!我有我的自定义 toast ,所以当我调用它时,我想调用这样的函数,例如 showToast("toast 上的文本") 我尝试这样做,但当我单击按钮时它没有显示,这是我的代码
private void customToast(String Content) {
Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(R.layout.activity_toast, null);
Toast customToast = new Toast(context);
TextView toastText = findViewById(R.id.toast_text);
Content = "";
toastText.setText(Content);
customToast.setView(customToastroot);
customToast.setDuration(Toast.LENGTH_LONG);
customToast.setGravity(Gravity.TOP, 0, 0);
customToast.show();
}
这是我由 JavaScriptInterface 调用的按钮,它工作正常,但添加(字符串内容)toast 后未显示!
public class WebViewJavaScriptInterface{
private Context context;
WebViewJavaScriptInterface(Context context){
this.context = context;
}
@JavascriptInterface
public void showToast() {
customToast("Thanks Allah");
}
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
}
这是我的activity_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="@drawable/toast"
android:alpha="0.80"
tools:ignore="UselessParent"
android:gravity="center_horizontal"
android:layout_marginTop="10dp">
<TextView
android:id="@+id/toast_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="this is the TextVie"
android:textSize="16sp"
android:textColor="@color/colorWhite"
android:layout_gravity="center"
android:fontFamily="@font/open_sans_semibold"
android:textStyle="bold"
tools:ignore="HardcodedText"/>
</LinearLayout>
</LinearLayout>
最佳答案
private void customToast(String Content) {
Context context = getApplicationContext();
LayoutInflater inflater = getLayoutInflater();
View customToastroot = inflater.inflate(R.layout. activity_toast, null);
Toast toast = Toast.makeText(context, Content, Toast.LENGTH_LONG);
toast.setView(customToastroot);
TextView text = customToastroot.findViewById(R.id.toast_text);
/*Here you can do anything with above textview like text.setTextColor(Color.parseColor("#000000"));*/
text.setText(Content);
toast.show();
}
关于java - 如何向特定的 toast 函数添加参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57929760/