I have a custom view (CoordinateGridView) that I am using in an XML layout (activity_trajectory.xml):
<com.android.catvehicle.CoordinateGridView
android:id="@+id/coordinateGrid"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" />
I am getting this error in the graphical editor: **.CoordinateGridView failed to instantiate.
This is my constructor in the custom view:
public CoordinateGridView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
hostActivity = (TrajectoryActivity) this.getContext();
}
And this is the Activity where I am setting the layout with a CoordinateGridView in it:
public class TrajectoryActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
removeActionBar();
setContentView(R.layout.activity_trajectory);
initializeViews();
loadSettings();
}
}
Any ideas about the issue here? It's frustrating not being able to see anything in the graphical editor because my custom view is blocking all the other views in the layout...
The reason why you get an error in your graphical layout is because graphical editor trying to instantiate your view using it's own Context and it gets ClassCastException. So you should use View.isInEditMode()
to deremine if view is in edit mode and then skip unnecessary steps. For example:
public CoordinateGridView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
this.setOnTouchListener(this);
if (!isInEditMode()) hostActivity = (TrajectoryActivity) this.getContext();
}
and the same thing you should use in other places, where you use hostActivity
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With