我有这种带有监听器的 Java 源代码。
public static class FragmentA extends ListFragment {
OnArticleSelectedListener mListener;
...
// Container Activity must implement this interface
public interface OnArticleSelectedListener {
public void onArticleSelected(int position);
}
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnArticleSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(
"Activity must implement OnArticleSelectedListener");
}
}
...
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mListener.onArticleSelected(position);
}
}
我以这种方式实现它:
public class MyActivity implements FragmentA.OnArticleSelectedListener {
...
@Override
public void onArticleSelected(int pos) {
// do something
}
}
所以,现在我想把它转换成 Scala。我想,我应该使用特质。[已解决:在这堂课中,我得到了错误onAttach
] not found: value OnArticleSelectedListener
:
class FragmentA extends ListFragment {
var mListener: OnArticleSelectedListener = null
...
trait OnArticleSelectedListener {
def onArticleSelected(position: Int)
}
...
override def onAttach(activity: Activity) {
super.onAttach(activity)
mListener = (OnArticleSelectedListener) activity;
}
...
override def onListItemClick(l: ListView, v: View, position: Int, id: Long) {
// Send the event to the host activity
mListener.onArticleSelected(position);
}
}
在活动中,我不知道如何“实现”特征。我知道关键字是“with”,但extends ... with FragmentA.OnArticleSelectedListener
会extends ... with OnArticleSelectedListener
显示错误not found: type FragmentA
或not found: type OnArticleSelectedListener
.
有人知道如何解决这个问题吗?