3

我想创建一个自定义视图(我称之为MyComplexView),例如RelativeLayout带有 a Imageview、 aTextView和 a 的 a Button

我想用布局声明一个xml,然后创建类:

MyComplexView extends RelativeLayout{...}

但我不知道我应该覆盖什么来指示应该膨胀哪个布局。

我怎样才能做到这一点?谢谢

4

5 回答 5

5

像这样的东西:

  1. 从超类添加构造函数。(只有上下文的用于以编程方式创建视图,其他用于在 XML 中添加视图时。

  2. 创建一个init()例如调用的方法并从每个构造函数中调用它。

  3. 在init方法里面做:

    LayoutInflater.from(context).inflate(R.layout.my_view_layout, this, true);

现在 inflate 附加参数实际上意味着:

true -> 在您的情况下将布局附加到根相对布局(专业提示:因此,如果您的布局根也是相对布局,则在 xml 中您可以只合并标签并在代码中对齐它们以便层次结构更简单)或任何你喜欢的布局。

this -> 将膨胀视图附加到您正在扩展的相对布局的布局。

它将自动附加到根 -> 扩展RelativeLayout。

然后你可以使用 findViewById 像:

this.findViewById(R.id.myView);
于 2012-06-18T14:55:50.280 回答
1

我不是 100% 确定你的主要目标是什么,所以我尽量做到彻底:

如果您想在其他布局中包含一个复杂的布局,那么您可以简单地定义my_complext_layout.xml, 并在您的其他布局中放置:

<include layout="@layout/my_complext_layout" />

如果您需要运行自己的代码,那么您可以简单地将这个布局的根设为MyComplexView,并且您可以在创建视图时运行代码。

If you have intended to let your code operate on the layout, then simply implement an OnGlobalLayoutListener and add it to your layout in your views constructor.

于 2012-06-18T14:56:36.347 回答
1

Implement a Constructor for the MyComplexView:

public MyComplexView(Context context, AttributeSet attrs){
    LayoutInflater inflater = LayoutInflater.from(context);
    inflater.inflate(R.layout.header_view, this, true);
    mHeaderView = (TextView)findViewById(R.id.header);
    if(mHeaderView != null)
        mHeaderView.setText("Test");

}

于 2012-06-18T14:56:43.900 回答
1

See Custom Components in the developer docs. In particular the Compound Controls section.

Once you've made your java file, in order to refer to it in xml you'll have to use a fully qualified packagename i.e:

<com.yourpackage.YourCustomView
android:layout_height="wrap_content"
android:layout_width="wrap_content" />
于 2012-06-18T14:57:48.703 回答
1

Creating a custom view usually is aimed to create a widget which doesn't exist yet. What you're trying to do is to have the same layout repeated at multiple places.

You have severall options to do that according to your context.

  1. If the layout is to be placed in a lest, just create your layout in a separate file, and use it in a ListAdapter. Take a look at the ListView Tutorial for this.

  2. If this layout is a generic layout to be embedded in multiple activities, try using a Fragment instead. Fragments are subparts of an activity, with their own views. Alternatively, you can just embed the layout in severall xml using the tag.

  3. If really you want a custom class and single widget, then you need to extend the View class. Extending a layout means you wan't to organize child widgets differently (for example, organize them in circle). Extending a View, you can have exactly what you want (button, image, text) organized always in the same way. But I won't lie to you, this will mean lot of work.

于 2012-06-18T14:58:52.323 回答