我创建了一个自定义视图。它在真实设备上工作得很好,但在设计模式下,eclipse说:
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
我的代码非常简单:
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>
如果我评论v.addView(rl);
eclipse正确显示我的观点。尽管我使用this.isInEditMode()
这个事实,但在我看来,eclipse会读取所有代码。也许,这是一个日食错误。如何使eclipse忽略超出this.isInEditMode()
条件的代码行?
答案 0 :(得分:0)
我已经替换了有问题的代码:
ViewGroup v = (ViewGroup)MyBanner.this;
v.addView(rl);
以下一个:
this.addView(rl);
现在eclipse显示我的观点没有错误。