适配器如何处理android中的空arrayList?

时间:2017-02-11 21:52:43

标签: java android arraylist

我有这段代码:

WordAdapter.java

  public class WordAdapter extends ArrayAdapter<Word>  {

        public WordAdapter(Context context, ArrayList<Word> words, int colorResourceId) {
            super(context, 0, words);
            mColorResourceId = colorResourceId;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Check if an existing view is being reused, otherwise inflate the view
            View listItemView = convertView;
            if (listItemView == null) {
                listItemView = LayoutInflater.from(getContext()).inflate(
                        R.layout.list_item, parent, false);
            }

            Word currentWord = getItem(position);


            TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view);

  miwokTextView.setText(currentWord.getMiwokTranslationId());


            TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view);

            defaultTextView.setText(currentWord.getDefaultTranslationId());


            ImageView imageView = (ImageView) listItemView.findViewById(R.id.image);
            if (currentWord.hasImage()) {
                // If an image is available, display the provided image based on the resource ID
                imageView.setImageResource(currentWord.getImageResourceId());
                // Make sure the view is visible
                imageView.setVisibility(View.VISIBLE);
            } else {
                // Otherwise hide the ImageView (set visibility to GONE)
                imageView.setVisibility(View.GONE);
            }

            // Set the theme color for the list item
            View textContainer = listItemView.findViewById(R.id.text_container);
            // Find the color that the resource ID maps to
            int color = ContextCompat.getColor(getContext(), mColorResourceId);
            // Set the background color of the text container View
            textContainer.setBackgroundColor(color);

            // Return the whole list item layout (containing 2 TextViews) so that it can be shown in
            // the ListView.
            return listItemView;
        }
    }

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        WordAdapter adapter = new WordAdapter(getActivity(),  new ArrayList<Word>(), R.color.category_phrases);

        ListView listView = (ListView) findViewById(R.id.list);

        listView.setAdapter(adapter);
}
}

我将空ArrayList<Word>传递给WordAdapter并运行我的应用程序,该应用程序向我显示一个白色屏幕(空列表)。为什么尝试在没有数据的适配器中调用getView()方法时应用程序不会崩溃?当数组列表为空时,适配器如何处理这种情况?

1 个答案:

答案 0 :(得分:1)

嗯,这很简单

getView()仅在count方法返回的值大于0时调用

当您添加空ArrayList时,您的count0,因此无法调用getView()