谁能指导一下,
如何在xml和java文件中创建自定义组件
从xml传递属性(这个我有点完成)
如何从新的 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/