Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Failed to instantiate a Custom View in XML

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.

Error in Android Graphical Editor

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...

like image 569
Tarif Haque Avatar asked Sep 11 '25 00:09

Tarif Haque


1 Answers

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.

like image 167
Desert Avatar answered Sep 12 '25 14:09

Desert