How to access xml layout in custom button
i'd appreciate any help with following.
i have created a custom component - MyButton class that extends Button. I can set attributes in the constructor but i don't want to do this. i would like to set attributes in xml layou开发者_运维知识库t file. how do i get the attributes into the constructor so that when i create a new button in an activity, the new button is created using the xml layout file?
i've tried using inflator but it does not work in class extending button. is there another way that does the same? - i've spent hours searching net but nothing satisfactory came up.
thanks in advance
clive
here's the code
public class CustomViewModify2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyButton myb = (MyButton)findViewById(R.id.mybutton1);
myb.setText("hello");
}
}
the class:
public class MyButton extends Button {
public MyButton(Context context) {
super(context);
this.setBackgroundColor(getResources().getColor(R.color.Red));
}
public MyButton(Context context, AttributeSet attrs) {
super(context, attrs);
this.setBackgroundColor(getResources().getColor(R.color.Yellow));
}
}
the main.xml`
<idig.za.net.MyButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/mybutton1"
/>
`
the button_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/my_button_layout">
<Button android:text="Button" android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:background="@color/Yellow" android:gravity="center"
android:width="100dp" android:textStyle="bold" android:textSize="24sp"
android:textColorLink="@color/Red"></Button>
I think in the xml you can specify
<packagename.MyButton
instead of
<Button
and you will be able to specify attributes as if it were a normal button. That's what i did in my app.
XmlPullParser parser = resources.getXml(myResouce);
AttributeSet attributes = Xml.asAttributeSet(parser);
and then call the second constructor.
See http://developer.android.com/reference/android/util/AttributeSet.html
精彩评论