我有一个包含4-5个子视图的RelativeLayout的xml布局。我想有一个自定义视图类基于此xml布局与自定义onclick listner。
我尝试过通过扩展RelativeLayout和将View作为成员来使用自定义类。在我的构造函数中,我膨胀了布局并将其分配给我的View成员。但我想让类本身类似于我膨胀的视图对象。(我说的有意义吗!)
我当前的代码类似于下面的代码:
public class CustomItemView extends RelativeLayout {
private Context context;
private View itemView;
public CustomItemView(Context context) {
super(context);
this.context = context;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(layout, null);
}
public View getView() {
return itemView;
}
}发布于 2012-11-23 21:35:14
实现它的一种简单方法是扩展FrameLayout并在构造函数中将膨胀的布局附加到自己(this):
public class MyView extends FrameLayout {
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.my_view, this);
}
// Your view logic here
}然后,您可以通过编程方式使用全新的视图:
MyView myView = new MyView(context);或者在XML布局中:
<packageName.MyView
android:layout_width="match_parent"
android:layout_height="match_parent" />https://stackoverflow.com/questions/13530164
复制相似问题