java - 添加一个 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 文件。
解决方案
要在 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);
}
推荐阅读
- javascript - 迭代 mongodb 文档时如何避免使用 forEach?
- php - 如何在 PHP 中格式化不同国家的邮政编码?
- sql - 根据案例陈述汇总结果
- tensorflow - 用tensorflow 2预测前得到模型提出的区域
- javascript - 是否可以更改 html 页面并仅显示选定的 iframe?
- xamarin - 使用 Prism 和 Xamarin 在 MVVM 中错误地绑定数据
- javascript - 使用 Axios 节点发布 Tableau REST API
- css - 如何为具有正弦运动和旋转的矩形设置动画?
- python - 如何计算 PySpark 中的行之间的差异?
- javascript - 转换 React useState hooks 以传入 props 并更新 prop 值