【发布时间】:2013-02-22 23:40:42
【问题描述】:
我创建了一个扩展 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>更改为<merge>来解决,但是我根本无法预览布局! - 我想在 java 中使用
isInEditor()函数(或任何它被调用的函数)来添加一些示例数据以用于预览目的,但我找不到告诉 XML 编辑器它应该显示预览的方法我的班级而不是实际的 XML。
我能想到的一个不满意的解决方案是创建一个空的preview.xml 文件,其中只有<com.foo.bar.MyView/>...但这似乎有点愚蠢。有没有更好的办法? (我并不像预览那样关心编辑,因为 - 让我们面对现实吧 - Eclipse/ADT 太慢且不稳定,无法使用图形布局编辑。)
【问题讨论】:
-
尝试添加另外 2 个构造函数(MyView(Context context){this(context,null);} 和 MyView(Context context, AttributeSet attrs){this(context,attrs,0);}
-
是的,这没什么区别。也不知道为什么会这样。现在我只使用
preview.xml解决方案。 -
解决方法有很长的路要走。如果您安装 IDEA 并导入您的项目,它将创建一个日志,显示在预览自定义类时遇到的错误。很多时候,我发现类在其构造函数中依赖于其他类。通过一些重新排列和一些额外的字段初始化,我总是设法让我的自定义布局正确预览。无论如何,祝你好运......
标签: android xml layout adt custom-component