2014-07-24 156 views
0

我有一个从Textview扩展的自定义类,现在我需要在xml中获取布局的值。我试过从XML的属性值获取值

public FontTextView(Context context, AttributeSet attrs) { 
    super(context, attrs); 
    setIncludeFontPadding(false); 
    int style = attrs.getAttributeIntValue(com.android.internal.R.styleable.TextAppearance_textStyle,-1); 
    init(style); 
} 

但我不能得到com.android.internal.R.styleable它说包不存在。我想我可以从包装外面访问它。

有没有什么办法从xml中获取样式?

styleable.TextAppearance_textStyle的值是-2001555这个改变还是我能够通过使用?得到正确的值?

int style = attrs.getAttributeIntValue(-2001555,-1) 
+1

没有,它会崩溃您的应用程序,因为这些ID是建立在编译时 – Blackbelt

+0

让我怎么得到的AttributeSet值的情况下的99%? –

+0

看看本教程是否有帮助:http://www.vogella.com/tutorials/AndroidCustomViews/article.html – luiscosta

回答

0

Tyr以这种方式获取属性值。请注意0​​索引的含义,如文档中所述。

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

    int[] attrsArray = new int[]{android.R.attr.textStyle}; 
    final TypedArray array = context.obtainStyledAttributes(attrs, attrsArray); 
    int style = array.getInt(0, -1); // returns 1 for bold, 2 for italic 
    array.recycle(); 
}