Monday 15 September 2014

android - how to define AttributeSet parameter for extended layout -



android - how to define AttributeSet parameter for extended layout -

i having problem understanding how instantiate custom layout in code. not know how define required attributeset parameter.

i have gone through official docs not wrap head around :

http://developer.android.com/training/custom-views/create-view.html http://developer.android.com/reference/android/util/attributeset.html

in activity, instantiate :

new mycustomlayout(getactivity(), attrs)

but how define attrs?

mycustomlayout.java

public class mycustomlayout extends linearlayout implements onclicklistener { ... ... public mycustomlayout(context context, attributeset attrs) { super(context, attrs); layoutinflater inflater = (layoutinflater) context.getsystemservice(context.layout_inflater_service); view view = inflater.inflate(r.layout.mycustomxmllayout, this, true); ... } ... }

mycustomxmllayout.xml

<?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="http://schemas.android.com/apk/res/android" > <textview android:id="@+id/txt_1" android:layout_width="60dp" android:layout_height="wrap_content" android:layout_weight="2" android:lines="1"/> <button android:id="@+id/btn_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:minheight="0dp" android:minwidth="0dp" android:background="@null" android:text="x" android:layout_weight="1" /> </merge>

firstly, should define custom attributes in res/values/attrs.xml, add together <declare-styleable>, example:

<declare-styleable name="mycustomlayout"> <attr name="showtext" format="boolean" /> <attr name="buttonposition" format="enum"> <enum name="left" value="0"/> <enum name="right" value="1"/> </attr> </declare-styleable>

now can set custom attrs via xml, this:

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://schemas.android.com/apk/res-auto"> <your.package.name.mycustomlayout android:layout_width="match_parent" android:layout_height="match_parent" custom:showtext="true" custom:buttonposition="left" /> </linearlayout>

and in constructor can grab attrs:

public mycustomlayout(context context, attributeset attrs) { super(context, attrs); typedarray = context.gettheme().obtainstyledattributes( attrs, r.styleable.mycustomlayout, 0, 0); seek { mshowtext = a.getboolean(r.styleable.mycustomlayout_showtext, false); mbuttonpos = a.getinteger(r.styleable.mycustomlayout_buttonposition, 0); } { a.recycle(); } }

if want set attrs programmatically, should create public getters/setters that:

private boolean mshowtext; private integer mbuttonpos; public void setbuttonpos(int pos) { mbuttonpos = pos; } public void setshowtext(boolean showtext) { mshowtext = showtext; }

after can set attrs programmatically:

mycustomlayout layout = new mycustomlayout(getactivity()); layout.setbuttonpos(0); layout.setshowtext(true);

android

No comments:

Post a Comment