Java android中有没有办法通过XMLandroid:id将字段设置为自定义视图

Java android中有没有办法通过XMLandroid:id将字段设置为自定义视图,java,android,xml,dependency-injection,Java,Android,Xml,Dependency Injection,例如,我有一个自定义按钮,希望将其连接到SeekBar: public class SeekBarButton extends ImageButton { SeekBar seekBar; public SeekBarButton(Context context) { super(context); } public SeekBarButton(Context context, AttributeSet attrs) { su

例如,我有一个自定义按钮,希望将其连接到SeekBar:

public class SeekBarButton extends ImageButton {

    SeekBar seekBar;

    public SeekBarButton(Context context) {
        super(context);
    }

    public SeekBarButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SeekBarButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public void setSeekBar(SeekBar seekBar) {
        this.seekBar = seekBar;
    }

    public SeekBar getSeekBar() {
        return seekBar;
    }
}
我可以在代码中执行此操作:

sbb = (SeekBarButton) rootView.findViewById(R.id.minus_red);
sbRed = (SeekBar) rootView.findViewById(R.id.sbRed);
sbb.setSeekBar(sbRed);
但是8个按钮会提供很多样板,我想要的是:

    <com.whatever.views.SeekBarButton
        ...
        whatToPutHere:seekbar="@+id/sbRed"  // like this? whatToPutHere?
        android:id="@+id/minus_red" />

    <SeekBar
        android:id="@+id/sbRed"

        ... />

我想你很接近了。在布局文件的第一个XML标记中(我的示例是一个
RelativeLayout
),您需要对“custom”进行引用:


然后,无论自定义图像按钮位于何处,您都需要:

<com.whatever.views.SeekBarButton
        ...
        custom:seekbar="@+id/sbRed"
        android:id="@+id/minus_red" />


如果您还不知道,您还需要在
project\res\values
文件夹中创建一个
seekBarButton.xml
文件。

最简单的方法是创建一个自定义的
视图组
,其中既包含
按钮
又包含
Seekbar
如果您无法做到这一点,无论出于何种原因,这里有一个解决方案:

有几个步骤可以实现这一点。首先,必须定义一个自定义XML属性,然后才能引用和使用该属性

编辑(或创建)
res/values/attrs.xml
。加:

<declare-styleable name="SeekBarButton">
    <attr name="seekbarId" format="integer" />
</declare-styleable>
最后,在布局文件的根视图组中添加

xmlns:app="http://schemas.android.com/apk/res-auto"
那么



注意您需要调用
((ViewGroup)getParent())。在
SeekBarButton
中的findViewById(mSeekbarId)
来实例化
SeekBar
,但是
SeekBarButton
构造函数中的
getParent()
将为空。因此,延迟
findViewById()
直到您需要
SeekBar

您可以按程序设置标记。但是我正在寻找通过xml按程序编辑xml是不可能的您可以为自定义组件创建自定义属性,如本例所示是的John,如果自定义属性具有“id”android:id=“@+id/sbRed,我需要这个实例吗?首先:我承认我对这个相当陌生。您是否有理由建议使用
app:seekband
而不是
custom:seekband
?我认为“定制”是必需的,但如果有其他方法可以实现相同的目标,我很高兴知道何时适合使用这两个选项中的每一个。谢谢。@Chamatake san您可以使用任何名称空间。重要的是它与您在根布局中设置的相同。例如,
xmlns:app
=
app:seekband
xmlns:custom
=
custom:seekband
private void init(Context context, AttributeSet attrs, int defStyleAttr) {
    if (attrs != null) {
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.SeekBarButton, defStyleAttr, 0);
        mSeekbarId = a.getResourceId(R.styleable.SeekBarButton_seekbarId, 0);
        a.recycle();
    }
}
xmlns:app="http://schemas.android.com/apk/res-auto"
<com.whatever.views.SeekBarButton
    android:id="@+id/minus_red"
    app:seekbarId="@+id/sbRed"
    ... />

<SeekBar
    android:id="@+id/sbRed"
    ... />