簡體   English   中英

嘗試在xml布局中使用自定義視圖時出現運行時InflateException

[英]runtime InflateException when trying to use a Custom View in xml layout

我一直在閱讀許多類似的問題,以嘗試找到解決方案,但是沒有運氣。

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);
}

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

如果我改變setContentViewMainActivitysetContentView(new MainGamePanel(this))並刪除AttributeSet從構造函數的參數,並刪除View.Inflate(context, R.layout.game, null); ,那么它可以工作,但是我想弄清楚如何在xml文件中使用自定義視圖。

看來您是在不斷擴大布局。 您可以在包含MainGamePanel的R.layout.game上設置ContentView,從而使包含MainGamePanel的R.layout.game膨脹。

您應該從onCreate方法中刪除View.inflate行。 據我所知,它什么也沒做。 您也不應顯式調用onFinishInflate 當MainGamePanel實例的填充實際完成時,將自動調用該方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM