【问题标题】:LayoutInflator error "incompatible types" in fragment [duplicate]片段中的LayoutInflator错误“不兼容的类型”[重复]
【发布时间】:2018-01-20 21:19:01
【问题描述】:

Typeface hero = Typeface.createFromAsset(getContext().getAssets(),"fonts/Hero Light.otf");

    for (int i = 0; i < tabLayout.getTabCount(); i++) {
        //noinspection ConstantConditions
   TextView tv=
  (TextView)LayoutInflater.from(this).inflate(R.layout.item_tab,null);
        tv.setTypeface(hero);
        tabLayout.getTabAt(i).setCustomView(tv);

    }

我在“this”处收到错误,提示类型不兼容。 Mainfragment 无法转换为上下文。 请帮忙,因为这是我在 Tablayout 上更改字体的唯一可行方法。

【问题讨论】:

标签: java android


【解决方案1】:

如果您的代码在 Fragment 中,请使用 getActivity(),因为这不适用于内部类。

【讨论】:

    【解决方案2】:

    这就是您更改字体的方式。 注意:我假设您使用的字体是兼容的。

    第一种方式:

    Typeface face = Typeface.createFromAsset(getAssets(),
                "fonts/epimodem.ttf");
    textView.setTypeface(face);
    

    第二种方式:

    textView.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
    

    无法将 Mainfragment 转换为上下文

    getActivity().getApplicationContext() 替换getContext()

    要访问资源,您首先要访问您的 Activity,您可以在其中通过执行 getActivity() 设置片段。要获得与 Activity 相同的应用程序上下文,请执行 getActivity().getApplicationContext()

    【讨论】:

      【解决方案3】:

      this 在内部类中不起作用。如果它是片段然后尝试 getActivity() 和活动尝试 YourActivity.this

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-16
        相关资源
        最近更新 更多