我创建了一个扩展的自定义视图RelativeLayout
,我想预览它在设计器中的外观。
java是这样的:
// The view for a snap in the search/browse fragment.
public class MyView extends RelativeLayout
{
public MyView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
LayoutInflater inflater = LayoutInflater.from(context);
inflater.inflate(R.layout.the_layout, this);
}
public void setData(String text)
{
mText.setText(text);
}
// *** Views ***
private TextView mText;
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
mText = (TextView)findViewById(R.id.text);
}
}
XML是这样的:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<!-- (And lots more views) -->
</RelativeLayout>
然而,这有一些问题:
- 这实际上创建了
RelativeLayout
一个RelativeLayout
无意义的内部。可以通过将 XML 更改<RelativeLayout>
为 a来解决,<merge>
但我根本无法预览布局! - 我想
isInEditor()
在 java 中使用该函数(或任何它被调用的函数)来添加一些示例数据以用于预览目的,但我找不到一种方法来告诉 XML 编辑器它应该显示我的类的预览而不是实际的 XML。
我能想到的一个不满意的解决方案是创建一个preview.xml
只包含其中的空文件<com.foo.bar.MyView/>
......但这似乎有点愚蠢。有没有更好的办法?(我并不像预览那样关心编辑,因为 - 让我们面对现实吧 - Eclipse/ADT 太慢且不稳定,无法使图形布局编辑可用。)