Xamarin.Forms FindViewById() 返回 null

问题描述

我正在尝试在我所做的 android 项目的布局文件中使用自定义字体创建吐司:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView 
        android:id="@+id/toastTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingTop="5dp"
        android:paddingLeft="15dp"
        android:fontFamily="@font/made_evolve_sans_light"
        android:textColor ="#424242"
        android:textSize="25sp"
    />
</LinearLayout>

然后对于我做的自定义吐司:

        Toast toast = Toast.MakeText(Application.Context,message,ToastLength.Long);
        TextView v = (TextView)toast.View.FindViewById(Resource.Id.toastTextView);
        v.SetTextSize(Android.Util.ComplexUnitType.Sp,25);
        toast.View.Background.SetColorFilter(Android.Graphics.Color.ParseColor("#F2e3dace"),PorterDuff.Mode.SrcIn);

        toast.SetGravity(GravityFlags.Center,0);
        toast.Show();

但是在运行时,textview v 始终为空。

如何通过 ID 找到带有自定义字体的文本视图?

谢谢!

解决方法

据我所知,toast 的 textview id 是:android.R.id.message

,

根据您的描述,您想在 Xamarin.forms 中使用自定义字体创建 Toast,您可以使用 DependencyService 来获取它。

在您的共享代码项目中,创建界面吐司:

public interface toast
{
    void Show(string message);
}

然后在Android平台上实现这个接口。您可以使用以下代码创建自定义字体 Toast。不要忘记注册平台实现。

[assembly: Xamarin.Forms.Dependency(typeof(Toast_Android))]
namespace FormsSample.Droid
{
public class Toast_Android : toast
{
    public void Show(string message)
    {
        
        Toast toast = Toast.MakeText(Application.Context,message,ToastLength.Long);
        TextView v = (TextView)toast.View.FindViewById(Android.Resource.Id.Message);
        v.SetTextSize(Android.Util.ComplexUnitType.Sp,25);
        toast.View.Background.SetColorFilter(Android.Graphics.Color.ParseColor("#F2e3dace"),PorterDuff.Mode.SrcIn);

        var typeface = Typeface.Create("customfont",Android.Graphics.TypefaceStyle.Bold);
        v.Typeface = typeface;

        toast.SetGravity(GravityFlags.Center,0);
        toast.Show();


    }
}
 }

对于 Android 原生平台,Toast 有一个文本视图:Android.Resource.Id.Message

然后就可以通过Button.click方法获取Toast:

private void btn2_Clicked(object sender,EventArgs e)
    {
        DependencyService.Get<toast>().Show("Toast Message");
    }

截图:

enter image description here