调用MainActivity.java的方法在事件发生在一个库文件
我包括图书馆滑动式,卡在我的Android项目的。在MainActvitiy.java在的onCreate 方法包括这样的事情:
I included the library Swipeable-Cards in my android project. In MainActvitiy.java the onCreate method includes something like that:
SimpleCardStackAdapter adapter = new SimpleCardStackAdapter(this);
//This should also be done on an event in the library class:
adapter.add(new CardModel("Title2", "Description2 goes here", r.getDrawable(R.drawable.picture2)));
现在,在CardContainer.java(属于滑动式卡库)有上,我希望有一个新的产品加入到适配器 adapter.add(...)。该适配器是在MainActvitiy.java定义,你可以看到上面。
我怎样才能做到这一点?
Now, in the CardContainer.java (which belongs to the swipeable cards library) there is an event on which I want a new item added to the adapteradapter.add(...)
. The adapter was defined in the MainActvitiy.java as you can see above.
How can I achieve this?
我首先想到的有关定义在MainActivity一种新的方法,然后从我的图书馆级调用它,这样的:
I first thought about defining a new method in MainActivity and then calling it from my library-class, like that:
public void callfromlibrary() {
adapter.add(...);
}
然而则方法和适配器需要定义静态的,另外不知道如何使MainActivity的这种方法在CardContainer.java可用。
However then the method and the adapter need to be defined static, additionally I don't know how to make this method of MainActivity available in CardContainer.java.
我相信我需要创建样的听众在什么CardContainer.java发生在MainActivity检查?我不知道如何做到这一点。
I believe I need to create kind of a listener to check in the MainActivity what happens in CardContainer.java? I don't know how to do this.
任何帮助AP preciated!
Any help is appreciated!
要允许 CardContainer
高达传达给 MainActivity
,您可以定义 CardContainer
接口>和 MainActivity
实现它>。当事件在 CardContainer
发生时,它可以调用,以便将 CardModel
添加到adapater接口方法。
To allow CardContainer
to communicate up to the MainActivity
, you define an interface in CardContainer
and implement it in MainActivity
. When the event occurs in CardContainer
, it can then call Interface method in order to add the CardModel
to the adapater.
public class CardContainer extends ... {
CardContainerEventListener mCallback;
// Define a interface
public interface CardContainerEventListener {
public void addToAdapter();
}
// Method to register callback
void registerCallback(Activity callback) {
mCallback = (CardContainerEventListener) callback;
}
void someFunction() {
// Event got generated, invoke callback method
mCallback.addToAdapter();
}
}
public class MainActivity extends Activity implements CardContainer.CardContainerEventListener {
// Ensure you register MainActivity with CardContainer, by calling
// cardContainer.registerCallback(this)
public void addToAdapter() {
adapter.add(...);
}
}