我有一个包含很多项目的 ScrollView。在它的底部,我添加了来自另一个 Activity 的一组项目。我检查来自另一个 Activity 的输入 ArrayList,并且应该使用 ScrollView 向我的 Activity 添加适当数量的复选框。我在 LinearLayout 的帮助下添加项目,如下所示:
public void addFiles()
{
adapter = new ArrayAdapter<File>(this,
R.layout.new_order, R.id.fileCheck,
FileManagerActivity.finalAttachFiles)
{
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// creates view
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.file, null);
view.setFocusable(false);
CheckBox textView = (CheckBox) view
.findViewById(R.id.fileCheck);
textView.setClickable(true);
textView.setText(FileManagerActivity.finalAttachFiles.get(position).getName().toString());
textView.setTextColor(Color.BLACK);
textView.setPadding(55, 0, 0, 0);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.file_icon, 0, 0, 0);
textView.setTextSize(16);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
textView.setCompoundDrawablePadding(dp5);
textView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
return view;
}
};
}
我知道不推荐在 ScrollView 中使用 ListView,但我尝试使用 LinearLayout 来达到我的目标,但效果不佳 - 它无法正确更新。为了以正确的方式显示 ListView,我使用了这样一个类:
public class UtilityListView {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
Log.i("ListAdapter count",Integer.toString(listAdapter.getCount()));
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
}
并在每次数据更改后使用它:
fileList = (ListView) findViewById(R.id.fileListView);
fileList.setAdapter(adapter);
UtilityListView.setListViewHeightBasedOnChildren(fileList);
但是 ListView 的高度远大于列表中的项目数量......我该如何解决?