Android : how to create custom component

纵饮孤独 提交于 2019-12-06 14:52:11

its very simple:

in your layout xml file simply put the following lines of xml code:

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

Now, write a class named as your component:

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
  }
}

Remember the constructor: this constructor is needed by the LayoutInflater to find your component. And, dont forget to call super(...) when required.

You can do this by calling the constructor with context in its parameter and then setting the attributes with getter setters. You can find a good tutorial at Android tech point

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

And then finally

layout.addView(myComponent);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!