如何在android中创建自定义和复合视图

rok*_*oid 2 android android-custom-view

我想在android中创建一个自定义和复合视图.我的自定义视图将包括1个textview,5个radiobuttons两个按钮和一些图像.我不知道怎么做.如果有一些示例或代码spinet,它会很好..

Vic*_*ngo 18

我认为它可以帮助你:

首先,您可以在xml中定义RelativeLayout,其中包含您想要的所有元素,并按您的需要放置.

其次,当你定义了这个布局时,你可以开发一个自定义类,扩展RelativeLayout,并在类的构造函数方法中扩展该布局,如下所示:

public class MyCustomView extends RelativeLayout {

 ...

 public MyCustomView(Context context) {

  LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

  addView(inflater.inflate(R.layout.your_layout, null));

  oneTextView = (TextView) findViewById(R.id.oneTextView);
  oneRadioButton = (RadioButton) findViewById(R.id.oneRadioButton);
  ...
 }
 ...
}
Run Code Online (Sandbox Code Playgroud)

此时,您可以以正常方式在您的类中使用oneTextView,oneRadioButton等.

  • 纠正我,如果我错了,但我不会以这种方式结束*两个*RelativeLayouts吗?毕竟,inflater会创建一个新的相对布局,然后添加到另一个RelativeLayout? (5认同)
  • 在这种情况下,您可以在your_layout http://developer.android.com/guide/topics/resources/layout-resource.html#merge-element中添加<merge>元素 (4认同)