如何使用ADT Eclipse插件在布局XML的图形预览中调试自定义 View ?
我编写了一个自定义 View ,将其放入布局XML中,然后可以在ADT Graphical Layout Editor中预览它。我可以查看自己的自定义 View ,就像Google家伙在Google I/O 2011: Android Development Tools中所做的一样。但是,我的自定义 View 在预览中的行为不正确(在模拟器/设备上没有问题,但我没有使用 View.isInEditMode()
)。我认为变量的值有误,但我无法确认。我试过了:
android.util.Log.d()
LogCat
或Console
中没有输出System.out.println()
LogCat
或Console
中没有输出Toast.makeText().show()
NullPointerException
在android.widget.Toast.show
throw new IllegalStateException(debugMessage)
(?!)debugMessage
没有出现在Error Log
中((Activity)getContext()).setTitle(debugMessage)
设置 Activity 标题((Activity)getContext()).getWindow().setTitle(debugMessage)
设置窗口标题NullPointerException
(window
是null
)TextView
final TextView textView = new TextView(getContext());
textView.setText(debugMessage);
this.addView(textView);
debugMessage
被显示,但是我的布局被破坏了ViewGroup
最佳答案
好问题!我也想知道。在布局编辑器中拥有良好的预览确实非常困难,而且似乎很少有文档说明当“isineditmode”为true时可以做什么和不能做什么(例如,构造函数上传入的AttributeSet中的自定义XML属性的解析)的 View 似乎不起作用,等等,等等)。
我什至在自定义 View 中按ID查找 View 时遇到问题。一个简单的事情像
mTextView = (TextView)myLayout.findViewById(R.id.view_id);
膨胀后,自定义 View 布局仅在从编辑器运行布局时才返回null(即isineditmode()== true)。在手机上运行该应用程序时,它可以工作。
我将您留在这里,这是在尝试在布局编辑器中更好地预览我的布局时的帮助:
1- 查找 View :我使用TAG属性,因为在编辑模式下findViewWithTag()函数确实起作用。所以我将ID用作TAG
<TextView
android:id="@+id/myTextViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
android:tag="mytextViewId" />
然后使用标记查找 View :
if(isineditmode()){
((TextView)myLayout.findViewWithTag("myTextViewId")).setText("Test text");
}
2- 检查一些值以了解为什么有时无法在编辑模式下实例化我的自定义 View ,或者检查是否可以在编辑模式下查询某些属性并知道它们的值。我在父布局中使用一个特殊的textview,它将在其中放置我的自定义 View ,并且将其隐藏并带有特殊标签:
<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>
这种线性布局将是我的自定义 View 的父级,而我需要在布局编辑器中打开该布局才能预览我的自定义 View 。 “调试” textview的可见性“消失”了,因此如果不需要,我不会打扰。
然后,当我需要检查某些内容时,请在自定义 View 的Java代码中执行以下操作:
if(isineditmode()){
TextView wDebugView = (TextView)this.getRootView().findViewWithTag("debug");
wDebugView.setVisibility(View.VISIBLE);
wDebugView.setText(Integer.valueOf(getPaddingTop()).toString());
}
在此示例中,我检查 View 的属性,例如顶部填充。
重要说明:您需要将值手动转换为String才能显示在“调试” View 中,否则它将崩溃并给您一个错误。
希望能帮助到你。
并且,如果有人对为什么无法通过id查找 View 有任何想法,那么将不胜感激。