我有ListView
的活动。
此ListView
的适配器我是从android.widget.BaseAdapter
:
public class SaleItemAdapter extends BaseAdapter {
...
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
SaleItem saleItem = saleItems.get(position);
if (saleItem.getFolder()) {
view = LayoutInflater.from(context).inflate(R.layout.list_folder_item, viewGroup);
TextView nameFolder = view.findViewById(R.id.nameFolder);
nameFolder.setText(saleItem.getName());
} else {
view = LayoutInflater.from(context).inflate(R.layout.list_sale_item, viewGroup);
}
return view;
}
问题是:我必须为LayoutInflater使用什么样的上下文?
我在实例化适配器对象getApplicationContext()
时尝试使用我的活动中的adapter = new SaleItemAdapter(this.getApplicationContext());
但是在这行代码之后它导致了我的应用程序崩溃:
view = LayoutInflater.from(context).inflate(R.layout.list_folder_item, viewGroup);
答案 0 :(得分:2)
首先,你必须像这样初始化LayoutInflater
apply plugin: 'android-sdk-manager'
apply plugin: 'com.android.application'
他们像这样夸大你的观点
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
答案 1 :(得分:0)
您必须在适配器类Context context
中创建constructor
的实例,然后使用此context
进行代码下面的布局检查
public class SaleItemAdapter extends BaseAdapter {
private Context context;
...
public DischargeAdapter(Context context){
this.context = context;
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
SaleItem saleItem = saleItems.get(position);
if (saleItem.getFolder()) {
view = LayoutInflater.from(context).inflate(R.layout.list_folder_item, viewGroup);
TextView nameFolder = view.findViewById(R.id.nameFolder);
nameFolder.setText(saleItem.getName());
} else {
view = LayoutInflater.from(context).inflate(R.layout.list_sale_item, viewGroup);
}
return view;
}
答案 2 :(得分:0)
我必须为LayoutInflater使用什么样的上下文?
您必须传递主要活动上下文。试试这个,
使用:
<强> MainActivity 强>:
adapter = new SaleItemAdapter(this);
<强> SaleItemAdapter 强>:
view = LayoutInflater.from(context).inflate(R.layout.list_sale_item, null);
而不是
<强> MainActivity 强>:
adapter = new SaleItemAdapter(this.getApplicationContext());
<强> SaleItemAdapter 强>:
view = LayoutInflater.from(context).inflate(R.layout.list_sale_item, viewGroup);
您的SaleItemAdapter应该定义一个构造函数,
public class SaleItemAdapter extends BaseAdapter {
private Context mContext;
public SaleItemAdapter (Context context){
mContext = context;
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
SaleItem saleItem = saleItems.get(position);
if (saleItem.getFolder()) {
view = LayoutInflater.from(mContext).inflate(R.layout.list_folder_item, null);
TextView nameFolder = (TextView) view.findViewById(R.id.nameFolder);
nameFolder.setText(saleItem.getName());
} else {
view =
LayoutInflater.from(mContext).inflate(R.layout.list_sale_item, null);
}
return view;
}