Android中的GridView没有填充

时间:2017-11-10 07:29:18

标签: android gridview adapter custom-adapter

我正在尝试使用自定义适配器填充我的gridView,但我不知道我做错了什么。它没有给出任何错误或任何错误。 gridView只是没有填充。起初我试图制作一个复杂的视图来插入但是。我认为这可能是问题的原因。但我甚至无法在其中插入单个textView。

public class MainActivity extends AppCompatActivity {

TextView v;
Button submitButton;
EditText e1,e2,e3;
DatabaseHelper dbHelper;
StringBuffer buffer;
Cursor res;
ArrayList<Book> list;
BookAdapter adapter;
GridView grid;


@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    buffer = new StringBuffer();
    Toolbar toolbar = findViewById(R.id.toolbar);
    grid = findViewById(R.id.grid);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("  Book Wizard");
    getSupportActionBar().setIcon(getDrawable(R.drawable.ic_action_local_library));
    list = new ArrayList<Book>();
    dbHelper = new DatabaseHelper(this);
    grid.setAdapter(new BookAdapter(MainActivity.this));
    fetchDB();
}

customAdapter类是: -

public class BookAdapter extends BaseAdapter {

    TextView textView;
    Context context;
    String[] names={"Looking for alaska","The alchemist","Lord of the rings"};

    BookAdapter(Context c){
        context = c;
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        textView = new TextView(context);
        textView.setText(names[position]);
        return textView;
    }
}

2 个答案:

答案 0 :(得分:1)

您以行数返回0

getCount方法更改为

@Override
public int getCount() {
    return names.length;
}

答案 1 :(得分:1)

按如下所示更改适配器,将计数作为数组的长度返回。

public class BookAdapter extends BaseAdapter {

TextView textView;
Context context;
String[] names = {"Looking for alaska", "The alchemist", "Lord of the rings"};

BookAdapter(Context c) {
    context = c;
}

@Override
public int getCount() {
    return names.length;
}

@Override
public Object getItem(int i) {
    return names[i];
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    textView = new TextView(context);
    textView.setText(names[position]);
    return textView;
}}