【问题标题】:adding a subclass of view in the main layout在主布局中添加视图的子类
【发布时间】:2015-10-14 00:04:59
【问题描述】:

这是主要布局文件的一部分:

<FrameLayout

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity = "center" >
    <view
        android:id="@+id/board"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        class="com.drawshapes.DrawCircles"></view>
</FrameLayout>

它给了我一个编译错误。我不确定我是否正确接近它。我应该看碎片吗?或者可能添加另一个活动文件?还是布局文件? 还有一个来自 google 的 sn-p 以这样的开头:

     <com.drawshapes.DrawCircles>
      android. .....
     </>

但我不知道将它们放在哪里,是否应该将它们放入资源文件或创建另一个布局文件。

感谢您的帮助。

【问题讨论】:

  • 粘贴你的 DrawCircle 类和错误日志

标签: android android-layout android-fragments android-intent


【解决方案1】:

试试这个

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center" >

    <com.drawshapes.DrawCircles
        android:id="@+id/board"
        android:layout_height="match_parent"
        android:layout_width="match_parent" />

</FrameLayout>

【讨论】:

  • 该标签仍然无效。错误指向 setContentView(R.layout.main_activity);在主要活动类中。
  • 你把DrawCircles类放在哪里?是库还是模块?
  • 我发现我做错了什么。事实证明,要在 XML 中添加视图的子类作为自定义视图,我们必须实现这个构造函数:public MyView (Context context, AttributeSet attrs)
【解决方案2】:

找到答案:

当实现要在布局 XML 文件中使用的视图子类时,请使用以下格式:

<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" >

<com.drawshapes.DrawCircles
    android:id="@+id/board"
    android:layout_height="match_parent"
    android:layout_width="match_parent" />

</FrameLayout>

(感谢 dotkebi。)

我还必须实现这个构造函数:

// gets called when adding this sub-view class from XML
  public DrawShapes(Context con, AttributeSet attrs) {
    super(con, attrs);
    Log.v("constructor", "context & attributes ");
    myList.add(new Shape(120, 170, 21,"square"));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多