【问题标题】:Custom view in xml layout not workingxml布局中的自定义视图不起作用
【发布时间】:2012-08-11 20:34:33
【问题描述】:

我正在尝试将 View 的子类添加到我的 activity_main.xml 中,例如 this

但是,设备和模拟器会立即退出应用。错误似乎是 Error inflating class com.example.androidtest.PuzzleView

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

<com.example.androidtestapp.PuzzleView
    android:id="@+id/puzzleView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="60"/>

<include
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="40"
    layout="@layout/activity_input"/>

</LinearLayout>

package com.example.androidtestapp;


public class PuzzleView extends View {


public PuzzleView(Context context) {
    super(context);
    setFocusable(true);
    setFocusableInTouchMode(true);


}
}

【问题讨论】:

  • 您也可以发布错误吗?
  • 我已经解决了这个问题,但我无法再发布 7 个小时的答案!我只需要将所有三个构造函数覆盖添加到类中,例如this
  • 你忘了构造函数? public PuzzleView(Context context, AttributeSet attrs)
  • 对不起,我在回答之前没有看到这些cmets。在我发表第一条评论后,我记得我过去也遇到过类似的问题。对不起。

标签: android xml layout


【解决方案1】:

我认为问题是你需要一个以 AttributeSet attrs 作为参数的构造函数

public PuzzleView(Context context, AttributeSet attrs) {
    super(context, attrs);
    //code
}

【讨论】:

  • 是的,我遇到了同样的问题,因为我知道您必须为扩展类实现所有构造函数,才能正常工作。
猜你喜欢
  • 2011-03-16
  • 1970-01-01
  • 2012-07-01
  • 2012-07-16
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 1970-01-01
  • 2013-03-29
相关资源
最近更新 更多