Android

custom-views with own attributes

A CustomView shall be given own values.
In the following example a string myString and a number myNumber.
In the javacode you get at these values by means of obtainStyledAttributes(..).



To that, a file data attrs.xml is compiled in the folder res/values, which defines these attributes:

<?xml version="1.0" encoding="utf-8">
 
<resources>
   <declare-styleable name="MyCustomView">
      <attr name="myString" format="string" />
      <attr name="myNumber" format="integer" />
   </declare-styleable>
</resources>



In the layoutfile myCustomView.xml in the folder res/layout values can be determined:

<?xml version="1.0" encoding="utf-8">
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res/com.sowas.javawiki"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   <com.sowas.javawiki.MyCustomView android:id=@+id/myCustomView"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      myString="Huhu"
      myNumber="1234"
   />
</LinearLayout>



In the java-code you can access attributes as follows:

package com.sowas.javawiki;
 
import ...
 
public class MyCustomView extends View {
 
   public MyCustomView(Context context, AttributeSet attrs) {
      super(context, attrs);
      TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
      String str = ta.getString(R.styleable.MyCustomView_myString);
      int number = ta.getInt(R.styleable.MyCustomView_myNumber);
      ta.recycle();
      System.out.println("The string: " + str);     // output: Huhu
      System.out.println("The number: " + number);  // output: 1234
   }
 
   .
   .
   .
}

Eigene Werkzeuge
Werkzeuge

gratis Counter by GOWEB
seit 9.10.2007