android - 如何从 xml 布局父级获取样式属性

标签 android android-layout

我在从 xml 布局的父元素获取自定义布局属性时遇到了很大的麻烦 好的,假设我有这样的布局

<com.blackstephen.customlayoutexperimental.StripedLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/stripedLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:divider_width="5dp">

<!-- put first view to left. -->
<TextView
    android:background="@mipmap/o"
    android:paddingStart="6dp"
    android:paddingEnd="6dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_position="left"
    app:percentage="40"
    android:text="@string/l1"/>
<com.blackstephen.customlayoutexperimental.StripedLayout/>

请注意,我在子 (TextView) 应用程序中有这些样式属性:layout_position="left" 应用程序:百分比=“40” 我可以通过将这个内部类放入自定义显示的代码中来获取这些值

 /**
 * Custom per-child layout information.
 */
public static class LayoutParams extends MarginLayoutParams {
    /**
     * The gravity to apply with the View to which these layout parameters
     * are associated.
     */
    public int gravity = Gravity.TOP | Gravity.START;
    public int position = 0;
    public int percentage = 33;

    public LayoutParams(Context c, AttributeSet attrs) {
        super(c, attrs);

        // Pull the layout param values from the layout XML during
        // inflation.  This is not needed if you don't care about
        // changing the layout behavior in XML.
        TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.StripedLayoutLP);
        gravity = a.getInt(R.styleable.StripedLayoutLP_android_layout_gravity, gravity);
        position = a.getInt(R.styleable.StripedLayoutLP_layout_position, position);
        percentage = a.getInt(R.styleable.StripedLayoutLP_percentage, percentage);
        a.recycle();
    }

但这只会给我每个 child 的样式属性 我还想要来自名为 app:divider_width="5dp"的父项的样式属性。 我该怎么做?

最佳答案

您可以在可绘制文件夹中创建一个 XML 文件,并将您想要的所有属性放入该 XML 中。如果你想要一个分隔线,在 drawable 中创建一个 divider.xml 并定义你想要的所有属性。然后用户 android:divider"@drawable/divider" 在 TextView 上调用这些属性。

示例:

<shape android:shape="rectangle"
xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/transparent" /> // color of the divider

在TextView中使用

    android:divider="@drawable/divider"
    android:dividerHeight="10dp"

关于android - 如何从 xml 布局父级获取样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50895901/

相关文章:

android - PhoneStateListener 事件有时会停止接收

android - 在应用程序启动时关闭抽屉导航

android - 如何设置 BottomNavigationBar 菜单项之间的间距相等?

android - 如何使文本在列表android上移到最右边

java - 在Java中设置editText的长度限制

java - Android 文本冒险应用程序 - 如何根据整数绘制不同的 XML 布局内容

android - 将 Button 移动到另一个 Button 的位置

android - 在不损失质量的情况下减小 Android 中位图的总大小

android - proguard 配置与 groundy Tasks

android - 动画完成后如何删除 Sprite ?