【问题标题】:Convert view into view that extends view将视图转换为扩展视图的视图
【发布时间】:2015-01-01 01:20:52
【问题描述】:

是否有可能在 xml 资源布局中有一个基本视图,并在对其进行膨胀以将其转换为特定视图时?

例如,有一个名为 MyCustomView 的自定义视图,它扩展了 EditText,以及一些扩展 MyCustomView 的视图,如 MyCustomViewNumber 或 MyCustomViewPassword 以及这样的布局:

<com.example.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    .....>
</com.example.MyCustomView>

是否有可能在我膨胀这个 xml 之后,MyCustomView 成为 MyCustomViewNumber 或 MyCustomViewPassword 之一(从这两个继承所有属性)。 MyCustomViewNumber 将是一个 EditText(最好是 MyCustomView),它在构造函数方法中已将输入类型设置为数字。

View baseView = LayoutInflater.from(getContext()).inflate(R.id.my_layout, container, false);
baseView = new MyCustomViewNumber(getContext()). //with this line I want that my view from the layout to take all attributes from MyCustomViewNumber.

概括:

public class MyCustomView extends EditText

public class MyCustomViewNumber extends MyCustomView { ctors > this.setInputType("number"); }

public class MyCustomViewPassword extends MyCustomView{ ctors &gt; same as above }

膨胀 MyCustomView。将膨胀视图设置为 MyCustomViewNumber 或 MyCustomViewPassword。有可能吗?

基本上我这样做是因为我需要“layoutParams”。我知道我可以从膨胀视图中获取布局参数,将其删除,然后添加具有该参数的新参数。

【问题讨论】:

  • 我不这么认为。您不能将基类转换为扩展类。只有反向是可能的。这将扼杀继承概念。
  • 你是对的。但我真的不想要那个。我想要的是从扩展类中获取属性集并将它们提供给基类​​。
  • 有点像,不是吗?基类的对象不能像这样获取其扩展类的属性。我觉得你应该找到另一种方法来实现你想要的。
  • 您在 XML 中声明的视图类必须由系统扩展,因此它必须知道确切类的名称,而不是接口或抽象类。所以这是不可能的。当然反过来。

标签: android android-layout


【解决方案1】:

不,您在 XML 中使用其完全限定名称的类已由系统实例化,因此必须是具体类。

【讨论】:

  • 相反,创建两个单独的类,并尝试将 CustomView(您的预期基类)中的共享行为提取到每个实际自定义视图可以使用的另一个类。
猜你喜欢
  • 2019-12-17
  • 1970-01-01
  • 1970-01-01
  • 2020-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多