【问题标题】:How can you associate an xml view to a java class?如何将 xml 视图关联到 java 类?
【发布时间】:2019-11-09 08:16:17
【问题描述】:
    <android.support.v7.widget.RecyclerView
        android:id="@+id/menu_list_rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone"
        >

    </android.support.v7.widget.RecyclerView>

考虑RecyclerView的例子,我们将上面的代码放在xml中,并像这样在java类中创建它的实例

menuListRV      = (RecyclerView)findViewById(R.id.sugg_rv);

在此之后,我们可以随心所欲地控制它。

现在我的问题是如何创建我自己的 xml 标记 &lt;xyz&gt;&lt;/xyz&gt; 可能具有一些属性并将类 XYZ 关联到它。

更新

我正在获取媒体播放器视图,但是当我将 xml 附加到它时,我没有得到更改,事实上我认为 xml 视图本身没有呈现。

public class ShortMediaPlayerControl extends ViewGroup {

    public ShortMediaPlayerControl(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate(context);
        Toast.makeText(context, "Coming 2", Toast.LENGTH_SHORT).show();
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ShortMediaPlayerControl, 0, 0);
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {

    }

    private void inflate(Context context) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.short_media_player, this, true);
    }

}

【问题讨论】:

标签: java android


【解决方案1】:

您需要创建类,继承自所需的小部件。在您的情况下,这是 RecyclerView。

public class MyCustomRecyclerView extends RecyclerView {
    ...
}

然后你可以像这样在 xml 中使用它:

 <com.example.yourapp.MyCustomRecyclerView 
    ...
           />

更新

也许迟到了,但看起来我明白你的意思了。所以是的,您可以像这样将您的自定义小部件类与 xml 相关联:

public class MyCustomRecyclerView extends RecyclerView {
        ...
    private void init(final Context context) {
        inflate(context, R.layout.your_custom_recycler_view_layout, this);
        ...
    }
}

【讨论】:

  • 我们可以在新类中使用 xml 吗?
  • @RateM,你是什么意思?如果您的类扩展了布局或小部件 - 是的,您可以在布局 xml 中使用它们。只需尝试创建您的类,添加所需的构造函数和方法(它们可能因类型而异),然后在您的布局 xml 中您可以使用您的小部件,其中标记将是您的类的完整包名称。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
相关资源
最近更新 更多