繁体   English   中英

Android片段中的自定义属性

[英]Custom attributes in Android fragments

我想在XML片段中使用XML(不使用捆绑包附加参数)在Android片段中定义自定义属性,例如在自定义控件中declare-styleable 但是没有带有AttrSet参数的构造函数,所以可能吗? 我是否可以重写public void onInflate(android.app.Activity activity, android.util.AttributeSet attrs, android.os.Bundle savedInstanceState)属性public void onInflate(android.app.Activity activity, android.util.AttributeSet attrs, android.os.Bundle savedInstanceState)以获得属性支持?

Support4Demos的链接已更改或可以更改,以便发布完整的解决方案。 来了

  1. 在res / values文件夹中创建attrs.xml文件。 或添加以下内容(如果文件已存在)。

     <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyFragment"> <attr name="my_string" format="string"/> <attr name="my_integer" format="integer"/> </declare-styleable> 

  2. 覆盖片段的onInflate委托并读取其中的属性

     /** * Parse attributes during inflation from a view hierarchy into the * arguments we handle. */ @Override public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) { super.onInflate(activity, attrs, savedInstanceState); Log.v(TAG,"onInflate called"); TypedArray a = activity.obtainStyledAttributes(attrs,R.styleable.MyFragment); CharSequence myString = a.getText(R.styleable.MyFragment_my_string); if(myString != null) { Log.v(TAG, "My String Received : " + myString.toString()); } int myInteger = a.getInt(R.styleable.AdFragment_my_integer, -1); if(myInteger != -1) { Log.v(TAG,"My Integer Received :" + myInteger); } a.recycle(); } 
  3. 如下将这些属性传递到布局文件中。 只是一个例子

     <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="This is android activity" /> <fragment android:id="@+id/ad_fragment" android:name="com.yourapp.packagename.MyFragment" android:layout_width="fill_parent" android:layout_height="50dp" android:layout_alignParentBottom="true" app:my_string="Hello This is HardCoded String. Don't use me" app:my_integer="30" /> </RelativeLayout> 

就这样。 它是一个可行的解决方案。

这样做时,如果您在xml中看到任何名称空间错误。 尝试一次又一次地清洁项目。 这是可悲的,但有时会出现日食和不良行为。

希望它对其他人有帮助:)

干杯

@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
    super.onInflate(activity, attrs, savedInstanceState); 
    // Your code here to process the attributes
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM