我创建了一个扩展Application的类,它存储了一个包含多个值的ArrayList。 该类用于在整个应用程序中存储值,因此我可以在需要时访问它们。
但是,我无法调用“getApplicationContext()'在我的自定义适配器类中,因为我收到以下错误:
错误:找不到符号方法getApplicationContext()
如果我是正确的,那是因为自定义适配器类不会扩展AppCompatActivity。
有人知道这方面的工作吗?最后,我尝试从存储的ArrayList创建一个ListView。
我的代码如下。
public class CartListAdapter extends ArrayAdapter<Product> {
private ArrayList<Product> products;
public CartListAdapter(Context context, int textViewResourceId, ArrayList<Product> products ) {
super(context, textViewResourceId, products);
this.products=products;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.activity_cart_row_item, parent, false);
final Global globalVariables = (Global) getApplicationContext();
//get product stored in array that exists in Application class
Product p = globalVariables.getMyProducts(position);
TextView name = (TextView) row.findViewById(R.id.cart_product_name);
TextView price = (TextView) row.findViewById(R.id.cart_product_price);
TextView quantity = (TextView) row.findViewById(R.id.cart_quantity_text);
TextView type = (TextView) row.findViewById(R.id.cart_type);
TextView option = (TextView) row.findViewById(R.id.cart_option);
name.setText(p.getProductName());
price.setText(p.getProductPrice());
quantity.setText(p.getProductQuantity());
type.setText(p.getProductType());
option.setText(p.getProductOption());
return row;
}
}
public class Global extends Application {
private ArrayList <Product> myProducts = new ArrayList<>();
private Cart cart;
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
public Product getMyProducts(int position) {
return myProducts.get(position);
}
public void addMyProducts(Product product) {
myProducts.add(product);
}
public int getMyProductsSize (){
return myProducts.size();
}
}
答案 0 :(得分:0)
您应该使用getApplicationContext()
,而不是使用getContext().getApplicationContext()
,因为您在ArrayAdapter
内使用了 static IObservable<int> ColdSource()
{
return Observable.Create<int>(subscriber =>
{
for (int i = 0; i <= 100; ++i)
{
subscriber.OnNext(i);
}
subscriber.OnCompleted();
return Disposable.Empty;
});
}
。