安卓 : how to create custom component

标签 android custom-component

谁能指导一下,

如何在xml和java文件中创建自定义组件

  1. 从xml传递属性(这个我有点完成)

  2. 如何从新的 customClass() 动态传递属性 -- 构造函数。 -- 我不知道如何实现这一点

例如:我创建了一个自定义组件,将两个 TextView 作为一个组件。在 xml 中,我通过 xml 属性创建了两个组件。现在我想通过 java 代码创建两个新组件 通过调用我的 customClass.java 的构造函数我不知道如何从 java 代码动态创建一个新组件以及如何在 View 中显示它(说一个相对布局)请帮我提供任何链接或博客。

我已经为此花了 1 个星期,但我没有得到任何解决方案请帮助我

最佳答案

非常简单:

在您的布局 xml 文件中,只需放入以下几行 xml 代码:

<com.example.project.MyComponent
  android:id="@+id/myid"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
/>

现在,编写一个名为您的组件的类:

public class MyComponent extends RelativeLayout {
  public MyComponent(Context context, AttributeSet attr) {
    super(context,attr);
  }

  @Override
  public void onFinishInflate() {
    // this is the right point to do some things with View objects,
    // as example childs of THIS View object
  }
}

记住构造函数:LayoutInflater 需要这个构造函数来 找到你的组件。并且,不要忘记在需要时调用 super(...)。

关于安卓 : how to create custom component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8985906/

相关文章:

java - Android - 在一部手机上压缩位图非常慢,在另一部手机上很快

android - 如何在 Activity View 中重绘 Canvas

android - xml中 fragment 中ListView上方的 float 操作按钮(FAB)?

android - 如何使用 Google Drive API : Insert File 上传 FILE_URI

java - 如何将标签绘制到自定义 JButton 上?

c# - 在进程终止时更新 SSIS 自定义组件中的变量不持久

java - JPanel 中的 JPanel 在不同位置被绘制两次

typescript - ionic 2 : Remove background from custom component button in navbar

delphi - 如何在对象检查器中对组件的属性进行分组?

java - Android 函数没有被调用