首页 > 解决方案 > 如何在 Unity Android 插件库中访问 AlertDialog 的消息和标题?(我在 AlertDialog 中使用自定义字体)

问题描述

我想在我的 android 插件库中使用自定义字体,同时使用AlertDialog. 现在这里是AlertDialog使用自定义字体显示的代码。

AlertDialog alertDialog = new AlertDialog.Builder(mainActivity).setTitle("Title").setMessage("Message Text").create();
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Cancel", dialogOnClickListener);

TextView alertMessageTextView = (TextView) alertDialog.findViewById(R.id.message); // I am getting error here
TextView alertTitleTextView = (TextView) alertDialog.findViewById(android.R.id.title); // I am getting error here

Typeface customFont = Typeface.createFromAsset(mainActivity.getResources().getAssets(), "fonts/lobster-regular.ttf");

alertMessageTextView.setTypeface(customFont);
alertTitleTextView.setTypeface(customFont);

alertDialog.show();

我收到错误:

Error Unity AndroidJavaException: java.lang.NoSuchFieldError: No static field message of type I in class Lcom/cptech/pluginexample/R$id; or its superclasses (declaration of 'com.cptech.pluginexample.R$id' appears in base.apk)

我已将字体文件放在 Unity 的“资产/资源”文件夹中。因此,在最终的 apk 中,字体资源出现在“assets/fonts”文件夹中。但是,这并不重要,因为我可以在其他TextView(s)中使用自定义字体。

唯一的问题是它找不到 AlertDialog 的消息和标题,我相信。任何帮助,将不胜感激。

标签: javac#androidunity3d

解决方案


几处改动:

在构建时使用show()而不是:create()AlertDialog

AlertDialog alertDialog = new AlertDialog.Builder(mainActivity).setTitle("Title").setMessage("Message Text").show();

然后,替换这一行:

TextView messageTextView = (TextView) alertDialog.findViewById(R.id.message);

android.R.id.message相反,像这样:

TextView messageTextView = (TextView) alertDialog.findViewById(android.R.id.message);

并确保您不会意外地import com.android.R在文件顶部进行操作。您需要进行此更改,因为 idmessage不是模块中的资产,它是 android 库中的默认资产。所以R你现在使用的是来自你的包 - 你需要指定Rfrom android.R

最后一件事,当你设置文本时注意textview的变量名,应该改为messageTextView


推荐阅读