我正在嘗試將表布局與 recyclerView 一起使用,但它給出了錯誤:java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TableRow.addView(android.view.View)' 在空對象引用上。有我的適配器類:public class CompanyAdapter extends RecyclerView.Adapter<CompanyAdapter.bookViewHolder> {ArrayList<DataClass> arrayList;TextView deposit;TextView purchase;TextView date;TableRow tableRow;TableLayout tableLayout;public CompanyAdapter(ArrayList<DataClass> arrayList){ this.arrayList = arrayList;}@Overridepublic bookViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); View view = LayoutInflater.from(context).inflate(R.layout.company_list_item,parent,false); return new bookViewHolder(view);}@Overridepublic void onBindViewHolder(bookViewHolder holder, int position) { DataClass dataClass = arrayList.get(position); holder.bind(dataClass); //bookNameTV.setText(dataClass.getBook()); //authorNameTV.setText(dataClass.getAuthor());}@Overridepublic int getItemCount() { return arrayList.size();}public class bookViewHolder extends RecyclerView.ViewHolder{ public bookViewHolder(View itemView) { super(itemView); deposit = (TextView) itemView.findViewById(R.id.deposit); purchase = (TextView) itemView.findViewById(R.id.purchase); date = (TextView) itemView.findViewById(R.id.date); tableLayout = (TableLayout) itemView.findViewById(R.id.maintablelayout); }還有一個問題,有沒有更好的方法可以在不使用任何庫的情況下將 tableLayout 與 recycler View 一起使用?謝謝..!
3 回答

忽然笑
TA貢獻1806條經驗 獲得超5個贊
TableRow
是一個實例變量,所以 JAVA 會在運行時用空值初始化它,你不能用空值調用任何方法。您必須將一個對象分配給TableRow
引用變量。
喜歡:
tableRow=new TableRow(context);

DIEA
TA貢獻1820條經驗 獲得超3個贊
您必須創建新的 TableRow
使用此代碼
TableRow tableRow=new TableRow(context);
tableRow.addView(deposit);
tableRow.addView(purchase);
tableRow.addView(date);
if(tableRow.getParent()!=null){
((ViewGroup)tableRow.getParent()).removeView(tableRow);
}
tableLayout.addView(tableRow, new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
添加回答
舉報
0/150
提交
取消