【问题标题】:How to Merge CustomFont Class with Material design Libary如何将自定义字体 Css 与材料设计库合并
【发布时间】:2016-04-04 05:59:23
【问题描述】:

我将在我的 xml 文件中使用的自定义按钮:

我想自定义一个矩形形状的按钮(来自 Material Design 库) 并为其添加自定义字体。

这就是我想出的:

import com.gc.materialdesign.views.ButtonRectangle;

public class FontCustomButton extends Button {

 public FontCustomButton(Context context, AttributeSet attrs) {
    super(context, attrs);

    MyButton myButton = new MyButton(context,attrs);
    Typeface typeface =  myButton.getFont(context);
    this.setTypeface(typeface);
 }

  //inner class
  public class MyButton extends ButtonRectangle{
    public MyButton(Context context) {
        super(context, attrs);

  }

        //this Method will return my font as TypeFace
        public Typeface getFont(Context context){

            Typeface face=Typeface.createFromAsset(context.getAssets(),"fonts/font_1.ttf");
            return face;
        }
  }

}

这是我希望它被称为的方式:

 <FontCustomButton 
        android:layout_width="140dp"
        android:layout_height="60dp"
        android:text="@string/log_in"
        android:id="@+id/btn_login"
         />

现在我的按钮应该同时具有矩形形状和字体。

我使用的 Material Design 库的链接:

https://github.com/navasmdc/MaterialDesignLibrary

【问题讨论】:

    标签: java android


    【解决方案1】:
    public class FontCustomButton extends ButtonRectangle {
    
    
     public FontCustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
         super(context, attrs, defStyleAttr);
         setCustomFont(context);
     }
    
     private void setCustomFont(Context context) {
        try {
            Typeface face = Typeface.createFromAsset(context.getAssets(), "fonts/font_1.ttf");            
            Field field = ButtonRectangle.class.getDeclaredField("textButton");
            field.setAccessible(true);
            TextView textView = (TextView) field.get(this);
            textView.setTypeface(face);
    
        } catch (Exception e) {
            e.printStackTrace();
        }
     }
    
    }
    

    【讨论】:

    • 如果您从 ButtonRectangle 扩展,setTypeface 将不起作用,因为 java 无法解析此方法。
    • 哦~对不起。我会改变我的答案:)
    • 可以通过getTextView()方法访问textButton,不需要反射
    • 我使用了 getTextView() ,但返回错误。我认为,如果你想要 getTextView() ,那么使用 super.getTextView() 。 (我不会尝试这种方式)
    • 非常感谢您,Kim :D 我刚刚学到了一个新东西,非常感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 2016-11-12
    • 2015-12-09
    • 2018-02-16
    • 2015-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多