Android : how to create custom component

℡╲_俬逩灬. 提交于 2020-01-03 03:57:06

问题


Any one please guide me,

How to create a custom component in xml and java file

  1. pass attributes from xml (this i somewhat completed)

  2. how to pass attributes dynamically from new customClass() -- constructor method. -- i dont know how to implement this point

for Eg : I created a custom component with two textview as a single component. In xml i created two component by xml attributes. Now i want to create two new component by java code by calling the constructor of my customClass.java I dont know how to create a new component dynamically from java code and how to display that in a view(Say a relative layout) Please help me provide any link or blog.

I have spent 1 week for this, But i didnt get any solution please help me


回答1:


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.




回答2:


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);


来源:https://stackoverflow.com/questions/8985906/android-how-to-create-custom-component

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