私はその問題に関するすべての研究を行った。グーグルはそれが無意味だと考えていること、そして開発者はそうではないことを知っていることを私は知っています。また、既知の回避策がないことも知っていますが、回避策を作成するところです。ユーザーDougWはこのコードを投稿しました:
public class Utility {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
それはほとんど私のために仕事を成し遂げます。しかし、試してみると、listItem.measure(0、0)行でNullPointer例外が発生します。listItem自体は初期化されますが、メソッドはとにかく例外をスローします。これを修正する方法を教えてください。
これが私のコードです:
public class ExpenseReportsActivity extends Activity {
private ListView lvReports;
private ExpenseReportListAdapter adapter;
private Button btnSend;
private Button btnCancel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expensereports);
lvReports = (ListView)findViewById(R.id.lv_reports);
lvReports.setBackgroundResource(R.drawable.shape_expense_report_list);
ColorDrawable cd = new ColorDrawable(0xFFffffff);
lvReports.setDivider(cd);
lvReports.setDividerHeight(1);
adapter = new ExpenseReportListAdapter(this);
lvReports.setAdapter(adapter);
int totalHeight = 0;
for (int i = 0; i < adapter.getCount(); i++) {
View listItem = adapter.getView(i, null, lvReports);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = lvReports.getLayoutParams();
params.height = totalHeight + (lvReports.getDividerHeight() * (adapter.getCount() - 1));
lvReports.setLayoutParams(params);
}
}
私が取り組んでいる別の回避策は、カスタムビューのonWindowFocusChangedメソッドを使用することです。ビューの正確な高さを示します。問題は、ActiviyのonCreateメソッドでも、ActivityのonWindowFocusChangedメソッドでも、イベントが発生しないことです。カスタムイベントを試しましたが、発生しませんでした(カスタムビューのonWindowFocusChangedメソッド内に配置され、リスナーはアクティビティのonWindowFocusChangedメソッド内にありました)。