Custom attributes in Android fragments

人走茶凉 提交于 2019-11-27 07:13:55

The Link for Support4Demos is changed or can be changed so posting the complete solution. Here it goes.

  1. Create attrs.xml file in res/values folder. Or add the below content if file already exists.

    <?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. Override the onInflate delegate of fragment and read attributes in it

    /**
     * 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. Pass these attributes in your layout file as following. Just an example

    <?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>
    

Thats all. Its a working solution.

While doing this if you see any namespace error in xml. try project cleaning again and again. This is pathetic but eclipse and adt misbehaves sometimes.

Hope it helps others :)

Cheers

@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
    super.onInflate(activity, attrs, savedInstanceState); 
    // Your code here to process the attributes
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!