尝试使用我创建的视图构建一个简单的网格。视图看起来像多米诺骨牌,这是定义它们扩展视图的类
public class Domino extends View{
private Paint paint;
public Domino(Context context) {
super(context);
init();
}
public void init(){
paint = new Paint();
paint.setTextSize(12);
paint.setColor(0xFF668800);
paint.setStyle(Paint.Style.FILL);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
invalidate();
}
}
然后在数组适配器中我尝试像这样构建它们
private class CustomAdapter extends ArrayAdapter<String> {
private Context mContext;
private int tileW, tileH;
private List<String> list = new ArrayList<String>();
public CustomAdapter(Context context, int textViewResourceId, List<String> objects) {
super(context, textViewResourceId, objects);
this.mContext = context;
this.list = objects;
// we need to do some calculation to get accurate screen dimensions if we're going fullscreen
DisplayMetrics displayMetrics = new DisplayMetrics();
((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
this.tileW = displayMetrics.widthPixels / 4;
this.tileH = tileW/2;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Domino domino;
if (convertView == null) {
// if it's not recycled, initialize some attributes
domino = new Domino(mContext);
domino.setLayoutParams(new GridView.LayoutParams(this.tileW, this.tileH));
domino.measure(this.tileW, this.tileH);
}
else {
domino = (Domino) convertView;
}
String colorString = list.get(position);
int rid = 0;
// figure out what color we're going to use
if (colorString.equals("r")) {
rid = R.drawable.grid_red;
}
else if (colorString.equals("o")) {
rid = R.drawable.grid_orange;
}
else if (colorString.equals("y")) {
rid = R.drawable.grid_yellow;
}
else if (colorString.equals("g")) {
rid = R.drawable.grid_green;
}
else if (colorString.equals("b")) {
rid = R.drawable.grid_blue;
}
else if (colorString.equals("i")) {
rid = R.drawable.grid_indigo;
}
else if (colorString.equals("v")) {
rid = R.drawable.grid_violet;
}
else {
rid = R.color.black;
}
return domino;
}
}
但是我没有看到任何内容,我想以编程方式设置数组适配器的高度和宽度。我错过了什么?
答案 0 :(得分:1)
// Replace this piece of code see what happens.
if (convertView == null) {
// if it's not recycled, initialize some attributes
domino = new Domino(mContext);
domino.setLayoutParams(new GridView.LayoutParams(this.tileW, this.tileH));
domino.measure(this.tileW, this.tileH);
convertView.setTag(domino);
} else {
domino = (Domino) convertView.getTag();
}