我有这样的代码,这只是一个带有事件监听器的类对象的示例类。
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style>
@font-face
{
font-family: Black Rose; src: url('BLACKR.TTF');
}
h3 {
font-family: 'Black Rose'
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" />
<br />
<h3>This is what the Image Font Looks Like</h3>
</div>
</form>
</body>
</html>
我的问题是: 如何在触发frag对象的事件时调用类MyActivity中的方法setText?
还是有另一种方法可以做到这一点?
任何答案都将不胜感激,谢谢!
答案 0 :(得分:2)
你可以这样做:
public class MyActivity ..... {
EditText something;
AnyFragment frag;
public MyActivity(){
frag = new AnyFragment(this);
}
public void setText(String text){
something.setText(text);
}
}
public class AnyFragment extends DialogFragment implements AnyListener{
private Context context;
public AnyFragment(Context context) {
this.context = context;
}
public void onEvent(String text){
((MyActivity)context).setText(text);
}
}
或使用interface
:
public class MyActivity ..... {
EditText something;
AnyFragment frag;
public MyActivity(){
frag = new AnyFragment();
frag.setFragListener(new AnyFragment.FragListener() {
@Override
public void notifyActivity(String text) {
setText(text);
}
});
}
public void setText(String text){
something.setText(text);
}
}
public class AnyFragment extends DialogFragment implements AnyListener{
private FragListener listener;
public setFragListener(FragListener listener) {
this.listener = listener;
}
public void onEvent(String text){
if(listener != null)
listener.notifyActivity(text);
}
public interface FragListener {
void notifyActivity(String text);
}
}