我想自定義ListView顯示圖像列表,所以我寫了下面的代碼,但不幸的是它不工作。ListView的圖像不工作
佈局/ menu.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:background="@drawable/menu_bg">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/name"
android:layout_gravity="center"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/menu_list"
android:layout_gravity="center"
android:layout_marginTop="60sp"></ListView>
</LinearLayout>
佈局/ menu_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/item"/>
</LinearLayout>
Menu.java
public class Menu extends Activity{
private int[] items = {R.drawable.res_opt, R.drawable.new_game_opt, R.drawable.score_opt, R.drawable.exit_opt};
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
list = (ListView) findViewById(R.id.menu_list);
list.setAdapter(new MenuAdapter(Menu.this, items));
}
}
MenuAdapter.java
public class MenuAdapter extends ArrayAdapter{
private int[] items;
private Context context;
public MenuAdapter(Context context, int[] items) {
super(context, R.layout.menu_item);
this.context = context;
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//make sure we have a view to work with
View itemView = convertView;
if(itemView == null)
{
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.menu_item,null, true);
}
//Find the object to work with
int id = items[position];
//Fill the view
ImageView item = (ImageView) itemView.findViewById(R.id.item);
item.setImageResource(id);
return itemView;
}
}
你有沒有試過用 「ItemView控件= inflater.inflate(R.layout.menu_item,父母,真);」 ? – Vink 2015-04-02 10:57:15
重寫getCount()並返回其中的數組大小。 – Manoj 2015-04-02 10:58:01
yup 1st我試過@Vink – 2015-04-02 11:01:47