在Eclipse可视化编辑器中创建自定义Android视图

11

在我的应用程序中,我经常依赖于自定义构建视图,例如以下示例。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:background="@color/light_grey"
android:layout_height="match_parent" 
android:layout_width="fill_parent" >

<TextView 
 style="@style/CardTitle" 
 android:id="@+id/card_title"
 android:layout_height="wrap_content" 
 android:layout_width="fill_parent"      
 />  

<com.whiterabbit.cards.ui.AspectRatioImageView
    android:id="@+id/card_picture"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:layout_marginLeft="30dip"
    android:layout_marginRight="30dip"       
    android:src="@drawable/boss"
    />



<ListView 
    android:id="@+id/card_properties" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"

/>

问题是,我不知道在真机或模拟器上运行时是否会正确显示。而且,如果我发现有什么问题,就必须对其进行更改并重新部署应用程序以查看更改是否按预期工作。

这可能是一个漫长而乏味的过程,特别是如果应用程序需要一些交互才能到达您想要检查的活动。

使用可视化编辑器无法加载自定义视图。

是否有另一种方法可以检查视图如何显示,而无需在整个应用程序中运行?


感谢@Blundell修改了我的问题。 - fedepaol
3个回答

56
你可以在你的自定义视图中实现这个功能:
if(!isInEditMode()){
   // Your custom code that is not letting the Visual Editor draw properly
   // i.e. thread spawning or other things in the constructor
}

http://developer.android.com/reference/android/view/View.html#isInEditMode()

这个方法允许你隐藏代码并在ADT插件XML查看器中显示布局。

View.isInEditMode()

指示此视图当前是否处于编辑模式。当这个View被展现在开发者工具内时,通常是在编辑模式下的。例如,如果该View被一个可视化用户界面构建器绘制,则此方法应返回true。子类应检查此方法的返回值,以便在其正常行为可能干扰宿主环境时提供不同的行为。例如:类在其构造函数中产生线程、绘图代码依赖于设备特定的功能等。此方法通常在自定义小部件的绘图代码中进行检查。


0

我正在使用Android Studio,所以我不确定这个答案是否适用于你的情况。

我认为你可以在自定义视图中重写onDraw方法,像这个例子一样保持内部图像的纵横比:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // TODO: consider storing these as member variables to reduce
    // allocations per draw cycle.
    int paddingLeft = getPaddingLeft();
    int paddingTop = getPaddingTop();
    int paddingRight = getPaddingRight();
    int paddingBottom = getPaddingBottom();

    int w = getWidth() - paddingLeft - paddingRight;
    int h = getHeight() - paddingTop - paddingBottom;

    w = w<h ? w : h;
    h = w;

    // Draw the example drawable on top of the text.
    if (dieDrawable != null) {
        dieDrawable.setBounds(paddingLeft, paddingTop,
        paddingLeft + w, paddingTop + h);
        dieDrawable.draw(canvas);
    }
}

这个方法在模拟器和设计师中都可以运行。

它也适用于任何重新绘制视图的事件(例如onSizeChanged,onLayout等)。


0

你可以创建一个骨架活动,仅加载你想要看到的视图,并填充足够的数据以使其显示。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接