listView只有图像

时间:2015-09-02 19:50:25

标签: android xml listview android-listview android-image

我正在尝试使用图像创建一个listView。请这不是一个愚蠢的问题,所以任何帮助表示赞赏。我认为我的代码是正确的,但是当我运行它时,它只显示contentView但是为空。它没有显示我告诉它显示的图像。我创建了java文件,然后创建了两个xml文件,一个是listView,它是java文件的contentView,另一个是listView的一行。

我的java文件:

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

public class Craft extends Activity {
int[]images={R.drawable.one,R.drawable.two,R.drawable.three,R.drawable.four,R.drawable.five,R.drawable.six,R.drawable.seven;

ListView listView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.craft);
    listView=(ListView)findViewById(R.id.listView);
    MyAdapter adapter=new MyAdapter(Craft.this,images);
    listView.setAdapter(adapter);

}
class MyAdapter extends ArrayAdapter<String> {

    Context c;
    int[] images;
    int count = 0;

    public MyAdapter(Context c,int imgs[]) {
        super(Craft.this, R.layout.single_row);
        this.c = Craft.this;
        this.images = imgs;

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View row = inflater.inflate(R.layout.single_row, parent, false);

        Log.d("Plates", "Count: " + count++);

        ImageView myImage = (ImageView) row.findViewById(R.id.imageView23);
        myImage.setImageResource(images[position]);

        return row;
    }

}
}

我的craft.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/woodcrop">
<ListView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:layout_gravity="center_vertical"
    android:layout_weight="1" />

我的single_row.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@drawable/woodcrop">
<ImageView
    android:layout_margin="20dp"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:src="@drawable/one"
    android:id="@+id/imageView23" />

感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

您应该将ListView高度更改为:

 <ListView
 .
 .
 .
 android:layout_height="match_parent"/>

我明白了,你的适配器中没有覆盖getCount(): 因此,您的列表视图不知道有项目。

您应该将其添加到您的适配器:

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

答案 1 :(得分:-1)

Ty使用这个超级声明
     超级(c,R.layout.single_row,imgs);