首页 > 解决方案 > 添加一个 BoardView 扩展 View 类到一个线性布局

问题描述

如何向 LinearLayout 添加视图?我有一个扩展 View 的名为 BoardView 的类,我想将它添加到 LinearLayout。我的代码如下所示:

protected void onCreate(Bundle savedInstanceState){
  super.onCreate(savedInstanceState);

  board = new Board();
  boardView = new BoardView(this, board);
  board.addObserver(boardView);
  setContentView(boardView);
}   

我尝试了这样的事情:

LinearLayout boardgame = (LinearLayout)  findViewById(R.id.boardgame);
linBoardGame.addView(boardview);
setContentView(boardgame);

不幸的是,这会返回 NullPointerException。添加的相同例外

<com.example.abc.def.BoardView  
android:id="@+id/view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>

到 game_activity.xml 文件。

标签: javaandroidxmlandroid-layout

解决方案


要在 a 中添加视图,ViewGroup您首先必须ViewGroup在 Activity 中有一个。
所以ViewGroup在 Activity 的 xml 中有一个。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content"
android:id="@+id/boardgame"
>



</LinearLayout>

然后将视图添加到ViewGroup.

protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.actity_layout);
    board = new Board();
    boardView = new BoardView(this, board);
    board.addObserver(boardView);
    LinearLayout boardgame = (LinearLayout)  findViewById(R.id.boardgame);
    linBoardGame.addView(boardview);
}

推荐阅读