我有让 ListAdapters 工作的经验,并在网上寻找有关自定义适配器与 GridView 接口的教程,但我似乎无法让我的工作。我在线路上收到 NullPointerException:
image.setBackgroundColor(Color.GREEN);
我的Activity和Adapter如下: FixtureActivity:
package net.blakely.paul.Hyperion;
import android.os.Bundle;
import android.widget.GridView;
import com.actionbarsherlock.app.SherlockActivity;
public class FixtureActivity extends SherlockActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fixtures);
FixtureItemAdapter fia = new FixtureItemAdapter(this, 6);
GridView grids = (GridView) findViewById(R.id.grids);
grids.setAdapter(fia);
}
}
FixtureItemAdapter:
package net.blakely.paul.Hyperion;
import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FixtureItemAdapter extends BaseAdapter {
private Activity context;
public int size;
private ImageView image;
private TextView label;
public FixtureItemAdapter(Activity context, int size) {
super();
this.context = context;
this.size = size;
}
public int getCount() {
// TODO Auto-generated method stub
return size;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.v("Hyperion","convertView is Null?="+Boolean.toString(convertView==null));
if (convertView == null) {
LayoutInflater inflater = context.getLayoutInflater();
convertView = (LinearLayout) inflater.inflate(net.blakely.paul.Hyperion.R.layout.outputitem, null, true);
image = (ImageView) convertView.findViewById(net.blakely.paul.Hyperion.R.id.imageView1);
Log.v("Hyperion","image is Null?="+Boolean.toString(image==null));
label = (TextView) convertView.findViewById(net.blakely.paul.Hyperion.R.id.textView2);
}
// Decide which channel this is and set information accordingly
image.setBackgroundColor(Color.GREEN);
label.setText("LABEL");
return convertView;
}
}
对此问题的任何帮助将不胜感激。物有所值。我发现我在第一次通过适配器运行时获得了 NPE,当 convertView 为空时,图像最终也为空。