【问题标题】:using setcontentview twice使用 setcontentview 两次
【发布时间】:2012-09-26 06:06:36
【问题描述】:

我想实现类似图表的结构。

对于条形图,我使用的是 no。按钮在我的主要活动中,因此输出如下:


然后我正在创建扩展 View 的新类,以便使用画布为图形绘制 x 和 y 轴,如下所示:

public class Draw extends View {

Paint paint = new Paint();

public Draw(Context context) {
    super(context);
    paint.setColor(Color.BLACK);
  }

@Override
public void onDraw(Canvas canvas) {

    canvas.drawLine(20, 50, 20, 200, paint);
    canvas.drawLine(20, 200, 200, 200, paint);
  }
}

但问题是,在我的主要活动中使用以下代码行之后:

Draw draw = new Draw(this);
setContentView(draw);

当我再次设置ContentView 时,我得到以下输出:


所以我的问题是如何整合这两个视图以获得以下输出:

还有其他方法可以做到这一点吗?
感谢任何帮助。

编辑

根据各种建议,我删除了

Draw draw = new Draw(this);
setContentView(draw);

来自我的活动类,而是将这些行放在主 xml 布局中。

<com.example.calci.Draw 
    android:id="@+id/draw" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" />

但我正在关注例外

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.calci/com.example.calci.CalciActivity}: android.view.InflateException: Binary XML file line #468: Error inflating class com.example.calci.Draw

Caused by: java.lang.NoSuchMethodException: Draw(Context,AttributeSet)
at java.lang.Class.getMatchingConstructor(Class.java:643)
at java.lang.Class.getConstructor(Class.java:472)
at android.view.LayoutInflater.createView(LayoutInflater.java:480)

编辑 2

通过在构造函数中添加AttributeSet attributeSet,我得到了想要的结果。

但是任何人都可以建议我是否应该使用画布中的按钮或矩形来绘制条形图。

请注意,我需要根据seekbar 值动态修改条形图的高度。

【问题讨论】:

  • 为什么不在图形的左下角画两条线。
  • 在视图类中不可能。我在活动课上用过两次...
  • 请检查有问题的 EDIT 2。

标签: android android-layout android-canvas paint bar-chart


【解决方案1】:

如果您使用 xml 进行条形图布局,您可以在其中包含新创建的视图,如下所示:

<view
    class="your.package.name.ProjectName$NameOfYourClass" 
    id="@+id/draw"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

更多关于使用自定义组件:http://developer.android.com/guide/topics/ui/custom-components.html

【讨论】:

  • @GAMA 尝试向视图类添加方法: public Draw(Context context, AttributeSet attributeSet) { super.Draw(context, attributeSet); }
  • 请检查有问题的 EDIT 2。
  • @GAMA 似乎使用按钮更容易,因为您不必重绘画布,但使用矩形更专业。如果要绘制矩形,请尝试在视图上使用 invalidate() 方法。
【解决方案2】:

要回答您的问题,您可以将Draw 视图包含在与条形图布局相同的布局中,可能包含在FrameLayout 中,并避免两次设置内容视图。

但是,在图表应用程序中使用按钮似乎更像是一种 hack。您也可以考虑在 Canvas 上绘制条形图,就像绘制轴一样。

【讨论】:

  • 请检查有问题的 EDIT 2。
  • 我会推荐使用 Canvas 来绘制条形图,因为您可以更好地控制条形的位置。请记住,当应用程序在不同分辨率的设备上运行时,很难将按钮定位在精确的坐标上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-06
  • 2014-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多