尝试对空对象引用调用虚拟方法android.view.ViewGroup $的LayoutParams android.view.View.getLayoutParams()'

问题描述 投票:-3回答:1

我想提出一个简单的Android列表视图应用程序,它会显示一些基本的名称,在列表视图。我的应用程序意外停止。该logcat的是显示这个错误。

Attempt to invoke virtual method 'android.view.ViewGroup$LayoutParams android.view.View.getLayoutParams()' 
    on a null object reference.

CustomAdapter

public class CustomAdapter extends BaseAdapter {

    Context context;
    String animals[];
    LayoutInflater inflater;

    public CustomAdapter(Context applicationContext, String[] animals){
        this.context = applicationContext;
        this.animals = animals;
        inflater = (LayoutInflater.from(applicationContext));

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

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

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

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflater.inflate(R.layout.listview, null);
        TextView textView = (TextView) view.findViewById(R.id.tv);
        textView.setText(animals[i]);
        return null;
    }
}

主要活动

public class MainActivity extends AppCompatActivity {

    ListView listView;
    String animals[]= {"Dog", "Cat", "Humans", "Monkey", "Rat", "Snake", "Elephant", "Giraffe", "Deer", "Tiger", "Lion","Cow", "Pig", "Goat"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView =(ListView) findViewById(R.id.lv);
        CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), animals);
        listView.setAdapter(customAdapter);
     }
}
java android listview
1个回答
3
投票

在这里,你做了错误

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflater.inflate(R.layout.listview, null);
TextView textView = (TextView) view.findViewById(R.id.tv);
textView.setText(animals[i]);
return view;
}

public long getItemId(int i) {
    return animals.length;
}

截图qazxsw POI

© www.soinside.com 2019 - 2024. All rights reserved.