AttributeSet是Android的一个类,用于获取和处理XML中的属性集合。在Android开发中,我们经常需要在XML中定义一些自定义属性,然后在Java代码中获取和使用这些属性。这时就可以使用AttributeSet来获取XML中定义的属性。
使用AttributeSet的步骤如下:
<LinearLayout 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"> <com.example.MyCustomView android:id="@+id/customView" android:layout_width="match_parent" android:layout_height="wrap_content" app:customAttribute="123" /> </LinearLayout> public class MyCustomView extends View { private int customAttribute; public MyCustomView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView); customAttribute = typedArray.getInt(R.styleable.MyCustomView_customAttribute, 0); typedArray.recycle(); } } 在上面的代码中,我们通过context.obtainStyledAttributes(attrs, R.styleable.MyCustomView)方法获取TypedArray对象,然后使用typedArray.getInt()方法获取自定义属性的值。
<com.example.MyCustomView android:id="@+id/customView" android:layout_width="match_parent" android:layout_height="wrap_content" app:customAttribute="123" /> 在上面的代码中,我们使用了app:customAttribute来设置自定义属性的值。
通过上述步骤,就可以在Java代码中使用AttributeSet获取和使用XML中定义的属性了。