【问题标题】:Android : how to create custom componentAndroid:如何创建自定义组件
【发布时间】:2012-02-17 15:28:48
【问题描述】:

请各位大神指导一下

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

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

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

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

我为此花了 1 周时间,但我没有得到任何解决方案,请帮助我

【问题讨论】:

    标签: android custom-component


    【解决方案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(...)。

    【讨论】:

    • 我不确定您的自定义标签是否有效,但我知道这有效:
    • 我的例子扩展了一个相对布局——你不必用 ImageViews、TextViews 或其他的子元素来填充它;)
    • @Andreas Bf - 感谢您的回复。 public MyComponent(Context context, AttributeSet attr) 当您从 xml 文件传递​​ attr 时,将调用此构造函数。这部分我完成了。我想从 java 代码(而不是从 xml 布局)创建组件。就像调用构造函数 public MyComponent(Context context){...}我必须从 java 代码中传递值/属性。
    【解决方案2】:

    您可以通过在其参数中使用上下文调用构造函数,然后使用 getter setter 设置属性来做到这一点。你可以在Android tech point找到一个很好的教程

    MyComponent mycomponent = new MyComponent(context);
    myComponent.setFirstTextView("text1");
    myComponent.setSecondTextView("text2");
    

    然后终于

    layout.addView(myComponent);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-23
      • 2017-05-23
      • 2011-11-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多