Search code examples
javaandroideclipseandroid-layoutandroid-custom-view

View.isInEditMode() doesn't skip code


I've created a custom view. It works perfect on real device, but in design mode eclipse says:

The following classes could not be instantiated:
- com.test.MyBanner (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.
Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse 

My code is very simple:

public class MyBanner extends WebView {

public MyBanner(Context context) {
    super(context);     
}

public MyBanner(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public MyBanner(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();         

    if(this.isInEditMode()){            
        getLayoutParams().height = 80;          
    }
    else{       
        getLayoutParams().height = 80;

        //Logotype----------------------------------------------
        RelativeLayout rl = new RelativeLayout(getContext());
        rl.setLayoutParams(getLayoutParams());

        RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(100, 100);

        rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

        ImageView logotype = new ImageView(getContext());                           
        logotype.setBackgroundColor(Color.TRANSPARENT);

        logotype.setImageResource(R.drawable.ic_launcher);
        rl.addView(logotype, rlp);

        ViewGroup v = (ViewGroup)MyBanner.this;
        v.addView(rl); //If I comment this it works perfect.        
    }
}       
}

xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:id="@+id/bannerContainer">

<TextView
        android:id="@+id/bannerHeader"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"            
        android:gravity="center"
        android:text="@string/banner_tab_text" />

 <com.test.MyBanner android:id="@+id/banner"
     android:layout_width="match_parent"
android:layout_height="wrap_content" 
android:layout_below="@id/bannerHeader"/>

</RelativeLayout>

If I comment v.addView(rl); eclipse shows my view correctly. Despite of that fact that I use this.isInEditMode() it seems to me that eclipse reads all code. Perhaps, this is a eclipse bug. How to make eclipse ignore the lines of code which are out of this.isInEditMode() condition?


Solution

  • I've replaced the problematic code:

     ViewGroup v = (ViewGroup)MyBanner.this;
     v.addView(rl);
    

    to the following one:

     this.addView(rl);
    

    Now eclipse shows my view without errors.