【问题标题】:runtime InflateException when trying to use a Custom View in xml layout尝试在 xml 布局中使用自定义视图时出现运行时 InflateException
【发布时间】:2012-11-07 20:52:55
【问题描述】:

我一直在阅读很多类似的问题,试图找到解决方案,但没有运气。

MainActivity.java

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.game);
}

游戏.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<View
    android:id="@+id/adView"
    android:background="@drawable/ad"
    android:layout_width="320dp"
    android:layout_height="50dp"
    />

<my.package.MainGamePanel
    android:id="@+id/gameView"        
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    /> </RelativeLayout>

MainGamePanel.java

public class MainGamePanel extends SurfaceView implements SurfaceHolder.Callback {

private MainThread thread;

public MainGamePanel(Context context, AttributeSet a) {
    super(context, a);
    View.inflate(context, R.layout.game, null);
    onFinishInflate();
    thread = new MainThread(getHolder(), this);
    setFocusable(true);
    thread.setRunning(true);

等等。等等

然后在MainGamePanel构造函数之外是函数:

@Override
protected void onFinishInflate() {
    getHolder().addCallback(this);
}

还有一个 MainThread.java 文件,但我认为这不是问题。

这是运行时异常:

java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.MainActivity}: android.view.InflateException: Binary XML file line #13: Error inflating class my.package.MainGamePanel

如果我将 MainActivity 中的 setContentView 更改为 setContentView(new MainGamePanel(this)) 并从构造函数中删除 AttributeSet 参数,并删除 View.Inflate(context, R.layout.game, null); ,那么它可以工作,但我想弄清楚如何使用xml 文件中的自定义视图。

【问题讨论】:

  • 看起来你在循环膨胀布局。你在R.layout.game上设置ContentView,里面包含了MainGamePanel,它膨胀了R.layout.game,里面包含了MainGamePanel等,这可能不是问题,但它是一个问题
  • 谢谢!我移动了 View.inflate(context, R.layout.game, null);进入 MainActivity,就在 setContentView 之后,所以它只会被调用一次,现在就可以工作了。非常感谢。
  • 我会将其移至答案以便您接受

标签: java android xml layout-inflater


【解决方案1】:

看起来您正在循环膨胀布局。你在 R.layout.game 上设置ContentView,它包含一个 MainGamePanel,它膨胀 R.layout.game,它包含一个 MainGamePanel 等。

您应该从 onCreate 方法中取出 View.inflate 行。据我所知,它什么也没做。你也不应该明确地调用onFinishInflate。当 MainGamePanel 实例的膨胀实际完成时,它会自动调用。

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 2017-11-28
    • 2012-07-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-16
    相关资源
    最近更新 更多