How to insert custom view into XML's LinearLay

2019-09-11 07:25发布

问题:

So I have a CustomView which is extended from View. And I have a linear layout from XML. The XML named example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res/jembalang.comfest.game"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <jembalang.compfest.game.GameThread
    android:id="@+id/game_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  </jembalang.compfest.game.GameThread>
  <Button 
    android:text="Button" 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content">
  </Button>
</LinearLayout>

And the code using the xml

setContentView(R.layout.cobagabung);
gameView = (GameThread) Jembalang.this.findViewById(R.id.game_view);
gameView.setFocusable(true);
gameView.setFocusableInTouchMode(
gameView.start();

I added the GameThread constructor if that's helping

public class GameThread extends View implements Runnable,OnKeyListener{
    public GameThread(Context context,AttributeSet attr){
        super(context, attr);
        ...
    }
    public GameThread(Context context) {
        super(context);
        ...
    }

I think there is something wrong with my way doing it, because the findViewById returns null How should I do to make my CustomView (GameThread at this example) to be able inserted into xml?

回答1:

Your line should read:

gameView = (GameThread) Jembalang.this.findViewById(R.id.game_view);

you are passing the id of a layout rather than that of the view you have created.

The rest of your code looks fine



回答2:

I don't know what Jembalang is but I think you should remove that.

gameView = (GameThread) findViewById(R.id.game_view);


回答3:

You say your layout file is called "example.xml", but you call setContentView(R.layout.cobagabung). Thus, your view is initialized from "cobagabung.xml".

Make sure you use the same identifier for layout file name and setContentView call, like

setContentView(R.layout.example);