代码是针对android但问题与Java有关我有一个派生类我想创建列表并传递给超级构造函数,同时保留子类中的引用
下面这段代码是我想要做的
public class AccountListAdapter extends ArrayAdapter<Account> {
private List<Account> cuentas;
private Context context;
private AccountListStore loginstore;
public AccountListAdapter(Context context) {
loginstore = new AccountListStore(context);
try {
cuentas = loginstore.getAccounts();
} catch (SQLException e) {
cuentas = new ArrayList<>();
e.printStackTrace();
}
//What I wana but I know is not posible
super(context, R.layout.acount_listadapter, cuentas);
}
Run Code Online (Sandbox Code Playgroud)
我想@spa的答案已经解决了你的问题.但是有些情况下你需要构造一个超级构造函数参数,但超类不允许你访问该值.
您可以通过创建一个静态帮助器方法来构造参数值和第二个私有构造函数来解决这个问题,您可以从公共构造函数中调用它:
public class AccountListAdapter extends ArrayAdapter<Account> {
private List<Account> cuentas;
private Context context;
private static List<Account> createCuentas(Context context)
{
AccountListStore loginstore = new AccountListStore(context);
try {
return loginstore.getAccounts();
} catch (SQLException e) {
e.printStackTrace();
return new ArrayList<>();
}
}
public AccountListAdapter(Context context) {
this(context, createCuentas(context));
}
private AccountListAdapter(Context context, List<Account> cuentas) {
super(context, R.layout.acount_listadapter, cuentas);
this.cuentas = cuentas;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
63 次 |
| 最近记录: |