Reputation: 4927
I have a xml layout with a RelativeLayout that holds 4-5 subviews. I want to have a custom View class based on this xml layout with a custom onclick listner.
I have tried with a custom class by extending RelativeLayout and by having a View as member. And in my constructor i'm inflating the layout and assigning it to my View member. But I want to have the class itself similar to my inflated view object. (did I make any sense!!)
my current code is similar to below:
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;
}
}
Upvotes: 1
Views: 2789
Reputation: 18670
One simple way to achieve it is to extend FrameLayout
and attach the inflated layout to oneself (this
) in the constructor:
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
}
Then you can use your brand new view programatically:
MyView myView = new MyView(context);
Or in an XML layout:
<packageName.MyView
android:layout_width="match_parent"
android:layout_height="match_parent" />
Upvotes: 5