gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:43:31 24 4
gpt4 key购买 nike

我有这段代码:

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;
}
}

主 Activity .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() 时不会崩溃没有数据的适配器中的方法?当数组列表为空时,适配器如何处理这种情况??

最佳答案

其实很简单

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

意思是当你添加一个空的ArrayList时,你的count0所以没有调用getView()制作

关于java - 适配器如何处理android中的空arrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42181655/

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