我写了一个自定义视图,放在一个布局XML中,我可以在ADT Graphical Layout Editor中预览它.我可以查看我的自定义视图,就像Google在Google I/O 2011: Android Development Tools中做的那样.但是,我的自定义视图在预览中的行为错误(没有问题在仿真器/设备上,但是我没有使用View.isInEditMode()).我认为一个变量有错误的价值,但我无法确认.我试过了:
> android.util.Log.d()
>在LogCat或Console中无输出
> System.out.println()
>在LogCat或Console中无输出
> Toast.makeText().show()
> NullPointerException at android.widget.Toast.show
>在我的自定义视图中设置断点
>在Eclipse中不会中断
> throw new IllegalStateException(debugMessage)(?!)
> debugMessage不会出现在错误日志中
>将活动标题设置为((Activity)getContext()).setTitle(debugMessage)
>没有效果
> ((Activity)getContext()).getWindow().setTitle(debugMessage)设置窗口标题
> NullPointerException(window为null)
>动态添加TextView
final TextView textView = new TextView(getContext()); textView.setText(debugMessage); this.addView(textView);
> debugMessage被显示,但我的布局被毁了
>仅在自定义视图为ViewGroup时才起作用
解决方法
我甚至在自定义视图中通过ID查找视图的问题.一个简单的事情像
mTextView = (TextView)myLayout.findViewById(R.id.view_id);
膨胀后,我的自定义视图布局只有在从编辑器运行布局(即isineditmode()== true)时才返回null.当在手机上运行应用程序时,它可以工作.
我在这里离开你在布局编辑器中尝试更好地预览我的布局时帮助我的东西:
1-查找视图:我使用TAG属性,因为findViewWithTag()函数在编辑模式下工作.所以我使用标识的标识
<TextView
android:id="@+id/myTextViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
android:tag="mytextViewId" />
然后使用标签查找视图:
if(isineditmode()){
((TextView)myLayout.findViewWithTag("myTextViewId")).setText("Test text");
}
2-检查一些值以了解为什么有时候我的自定义视图无法在编辑模式下实例化,或者检查一些策略是否可以在编辑模式下查询并知道其价值.我在我的自定义视图放置的父布局中使用了一个特殊的文本视图,并将其隐藏并使用了一个特殊的标签:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
...
<com.example.myCustomView ... />
...
<TextView
android:id="@+id/DebugView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="debug"
android:textSize="16sp"
android:textColor="#FFFFFF"
android:visibility="gone"
/>
</LinearLayout>
此线性布局将是我的自定义视图的父项,而我需要在布局编辑器中打开以预览我的自定义视图. “调试”textview的可见性是“走了”,所以如果不需要,我不会打扰.
然后,当我需要检查我在自定义视图的java代码中执行以下操作时:
if(isineditmode()){
TextView wDebugView = (TextView)this.getRootView().findViewWithTag("debug");
wDebugView.setVisibility(View.VISIBLE);
wDebugView.setText(Integer.valueOf(getPaddingTop()).toString());
}
在这个例子中,我检查视图的属性,如顶部填充.
重要注意事项:您需要手动将String转换为“debug”视图中显示的值,否则会崩溃并给您一个错误.
希望它有帮助.
如果任何人有一些想法,为什么通过id找到意见不起作用,任何帮助将不胜感激.