Pan*_*ang 16 eclipse android adt android-custom-view android-layout
我编写了一个自定义视图,将其放在布局XML中,我可以在ADT图形布局编辑器中预览它.我可以查看自定义视图,例如Google员工在Google I/O 2011中的表现:Android开发工具.但是,我的自定义视图在预览中表现不正确(模拟器/设备没有问题,但我没有使用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)getContext()).getWindow().setTitle(debugMessage)
NullPointerException
(window
是null
)TextView
动态添加
final TextView textView = new TextView(getContext());
textView.setText(debugMessage);
this.addView(textView);
Run Code Online (Sandbox Code Playgroud)
debugMessage
显示,但我的布局被毁了ViewGroup
好问题!我也想知道.在布局编辑器中有一个很好的预览非常困难,而且当"isineditmode"为真时,它似乎很少关于你能做什么以及你不能做的文档(例如,在构造函数的传入AttributeSet中分析自定义XML属性)的意见似乎不起作用,等等).
我甚至在自定义视图中通过ID查找视图时遇到问题.一个简单的事情就像
mTextView = (TextView)myLayout.findViewById(R.id.view_id);
Run Code Online (Sandbox Code Playgroud)
在膨胀之后,我的自定义视图布局仅在从编辑器运行布局时返回null(即isineditmode()== true).在手机上运行应用程序时,它可以运行.
我在这里留下了什么帮助我在布局编辑器中更好地预览我的布局:
1- 查找视图:我使用TAG属性,因为findViewWithTag()函数在编辑模式下可以正常工作.所以我使用ID作为标签
<TextView
android:id="@+id/myTextViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
...
android:tag="mytextViewId" />
Run Code Online (Sandbox Code Playgroud)
然后使用标记查找视图:
if(isineditmode()){
((TextView)myLayout.findViewWithTag("myTextViewId")).setText("Test text");
}
Run Code Online (Sandbox Code Playgroud)
2- 检查一些值以了解为什么有时我的自定义视图无法在编辑模式下实例化,或者检查是否可以在编辑模式下查询某些属性并知道它们的值.我在父布局中使用了一个特殊的textview,我的自定义视图将放置在该布局中,我将其隐藏并带有一个特殊标记:
<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>
Run Code Online (Sandbox Code Playgroud)
这个线性布局将是我的自定义视图的父级,以及我需要在布局编辑器中打开以便预览我的自定义视图的布局."调试"textview visibilty"消失了"所以如果不需要我不会打扰.然后,当我需要检查一些东西时,我在自定义视图的java代码中执行以下操作:
if(isineditmode()){
TextView wDebugView = (TextView)this.getRootView().findViewWithTag("debug");
wDebugView.setVisibility(View.VISIBLE);
wDebugView.setText(Integer.valueOf(getPaddingTop()).toString());
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我检查视图的属性,如顶部填充.
重要说明:您需要在"调试"视图中手动将要显示的值转换为String,否则它将崩溃并给您一个错误.
希望能帮助到你.
如果有人知道为什么通过id查找视图不起作用,那么任何帮助都会受到赞赏.
归档时间: |
|
查看次数: |
5339 次 |
最近记录: |