gpt4 book ai didi

java - ListView 适配器不工作,未调用 getView。

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:46:55 26 4
gpt4 key购买 nike

我觉得我快疯了。将自定义适配器绑定(bind)到 Listview 如此简单的事情让我很头疼。

贴出代码然后解释一下:

主 Activity .java

package com.example.pruebalist;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

private static String[] data = new String[] {"0","1","2","3"};

public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Log.v("MainActivity","Inside MainActivity");
setContentView(R.layout.main);
ListView lstView = (ListView)findViewById(R.id.listNoticias);

ArrayAdapter<String> adapter = new LstAdapter(this, R.layout.row, data);
lstView.setAdapter(adapter);
}

}

LstAdapter.java

package com.example.pruebalist;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class LstAdapter extends ArrayAdapter<String>{

private String[] mData;
private Context mContext;
int layoutResourceId;

public LstAdapter(Context context, int textViewResourceId, String[] values) {
super(context, textViewResourceId, values);
mContext = context;
mData = values;
layoutResourceId = textViewResourceId;

Log.v("LstAdapter","Inside LstAdapter");
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
Log.v("LstAdapter","Inside getView");

if(v==null){
LayoutInflater inflater = ((Activity)mContext).getLayoutInflater();
v = inflater.inflate(layoutResourceId, parent,false);
}

String item = mData[position];
if(item!=null){
TextView txtItem = (TextView)v.findViewById(R.id.texto);
if(txtItem!=null){
txtItem.setText(item);
}
}

return v;
}

}

ListView 永远不会显示。并且从未使用过 getView,logCat 不显示“Inside Getview”。

怎么了?

最佳答案

主要问题是

@Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

改成

@Override
public int getCount() {
// TODO Auto-generated method stub
return mData.length;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return mData[arg0];
}

看看这个 Vogella Tutorial on List View & List Activity ,尝试在 List Adapter 中使用 ViewHolder 它将提高您的 View 性能。

关于java - ListView 适配器不工作,未调用 getView。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12038660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com