简体   繁体   English

如何在“主要活动”中调用myCustomAdapter的公开身份?

[英]How to call public methood of myCustomAdapter in Main Activity?

I have MainActivity and Adapter. 我有MainActivity和适配器。 When new instance of the adapter is created I create new realm. 创建适配器的新实例后,我将创建新领域。 How can I close the realm in onDestroy methood? 我该如何关闭onDestroy模式? Heres what i tryed: 这是我尝试过的:
MainActivity's onCreate: MainActivity的onCreate:

public class MainActivity extends AppCompatActivity {
private ExpandableListView myELV;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    final android.support.v7.app.ActionBar actionBar = this.getSupportActionBar();
    myELV = findViewById(R.id.expandable_list_view);
    myAdapter adapter = new myAdapter(getApplicationContext());
    myELV.setAdapter(adapter);

The adapter: 适配器:

public class myAdapter extends BaseExpandableListAdapter{
private Context context;
private Realm realm;


public myAdapter(Context context){
    this.context = context;
}
public void closeRealm(){
    realm.deleteAll();
    realm.close();
}

MainActivity's onDestroy: MainActivity的onDestroy:

    @Override
protected void onDestroy() {
    super.onDestroy();
    ExpandableListAdapter adapter = myELV.getExpandableListAdapter();
    adapter.closeRealm();
}    

But closeRealm() is unaccessable even tho it is public. 但是即使公开,也无法访问closeRealm()。 And I want to know why? 我想知道为什么?

Echoing, @EpicPandaForce's answer, ExpandableListAdapter is the interface type. 回响@EpicPandaForce的答案, ExpandableListAdapter是接口类型。 Your closeRealm() method isn't one of the methods in that interface. 您的closeRealm()方法不是该接口中的方法之一。 One thing you could do to fix this is create aa new interface that extends ExpandableListAdapter, and lists the signatures for the new public methods you want there. 要解决此问题,您可以做的一件事情就是创建一个扩展ExpandableListAdapter的新接口,并在其中列出所需的新公共方法的签名。 Then any class that implements your new interface can be swapped for any other class that implements your new interface. 然后,可以将实现您的新接口的任何类替换为其他实现您的新接口的类。

Yes, using @EpicPandaForce's answer, I will post the change in the code if somebody is wondering in future: 是的,使用@EpicPandaForce的答案,如果将来有人想知道的话,我将在代码中发布更改:

    @Override
protected void onDestroy() {
    super.onDestroy();
    myAdapter adapter =  (myAdapter) myELV.getExpandableListAdapter();
    adapter.closeRealm();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM