I find myself needing to create a View completely in Java without knowing what concrete type the parent is.
example:
public View getView(int position, View convertView, ViewGroup parent){
if(null == convertView){
convertView = new TextView(parent.getContext());
}
((TextView) convertView).setText(getItem(position).getName());
}
Now suppose I wanted to change this so that the convertView was wrap_content in both directions. Since this is an Adapter, I’d like to avoid coupling the Adapter with the concrete type of the parent, but the LayoutParams I give it in setLayoutParams() has to be the correct concrete type otherwise the app will crash (i.e. if parent is a ListView it has to be ListView.LayoutParams, if it’s a LinearLayout it must be a LinearLayout.LayoutParams, etc.). I don’t want to use a switch statement either since that’s just a more flexible form of coupling, and if I attach this adapter to a view I didn’t anticipate I still end up with a crash. Is there a generic way to do this?
You can do this using the following code:
EDIT:
The method above doesn’t work because
ViewGroup.generateLayoutParams()requiresandroid:layout_widthandandroid:layout_heightto be set in the passedAttributeSet.If you useViewGroup.LayoutParamswith any layout then everything will work fine. But if you useLinearLayout.LayoutParamswithRelativeLayoutfor example, then an exception will be thrown.EDIT:
There’s one working solution for this problem which I don’t really like. The solution is to call
generateLayoutParams()with validAttributeSet. You can create anAttributeSetobject using at least two different approaches. One of them I’ve implemented:res\layout\params.xml:
SomeActivity.java:
Another way to create an
AttributeSetobject is to implementAttributeSetinterface and make it returnandroid:layout_width,android:layout_heightand other layout attributes you need.