当我注释掉setContentView(boardView);在我的Game.java中,BoardView中的自定义视图可以正常工作,并且可以很好地显示所有内容...但是onSizeChanged从未在BoardView.java中被调用...,因此我无法在运行时读取设备的宽度和高度。如果我不评论setContentView,onSizeChanged可以工作...但是屏幕空白!
我希望能够在运行时读取屏幕的宽度和高度,并在创建时设置ImageViews的大小,以便它们是最佳大小。
public class Game extends Activity implements OnClickListener{
private BoardView boardView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boardView = new BoardView(this);
setContentView(boardView); // when this line disabled, it looks ok
boardView.requestFocus();
}
public class BoardView extends View {
private final Game game;
private float width; // width of one unit
private float height; // height of one unit
public BoardView(Context context){
super(context);
this.game = (Game)context;
setFocusable(true);
setFocusableInTouchMode(true);
LinearLayout maincontainer = new LinearLayout(game);
maincontainer.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
maincontainer.setGravity(Gravity.CENTER);
maincontainer.setOrientation(LinearLayout.VERTICAL);
maincontainer.setBackgroundColor(Color.BLACK);
LinearLayout innercontainer = new LinearLayout(game);
innercontainer.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
innercontainer.setGravity(Gravity.CENTER);
innercontainer.setOrientation(LinearLayout.HORIZONTAL);
// declare a new table
TableLayout layout = new TableLayout(game);
layout.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
// build a grid of ImageViews in a TableLayout
for (int f=1; f<=7; f++) {
TableRow tr = new TableRow(game);
for (int c=1; c<=7; c++) {
ImageView b = new ImageView(game);
b.setImageResource(R.drawable.neworb);
b.setOnClickListener(game);
tr.addView(b, 30,30); // I'd like to not use fixed values here
} // for
layout.addView(tr);
} // for
innercontainer.addView(layout);
maincontainer.addView(innercontainer);
game.setContentView(maincontainer);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh){
width = w/9f;
height = width;
super.onSizeChanged(w, h, oldw, oldh);
}
}
}
最佳答案
以为我解决了自己的问题。我忽略了使用Overriden onDraw方法放置我的视图构建代码。即:
@Override
protected void onDraw(Canvas canvas)
{
LinearLayout maincontainer = new LinearLayout(this.game);
// etc..
我只是将其包含在主类中,而不是覆盖onDraw ...,这是在扩展View时必须执行的操作。
关于android - 自定义 View 未出现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2933219/