对于您中的许多人来说,这可能是一个愚蠢的问题,但是我找不到在RecyclerView适配器中使用getLifecycle()。addObserver()的方法。
答案 0 :(得分:2)
我试图对YouTubePlayerView做同样的事情,但发现了一种优雅的方法:
首先,您需要创建一个接口:
package main.app.view;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.Border;
import main.java.controllers.MapController;
import main.java.models.MapModel;
import main.resources.ConnectionManager;
public class MapView extends JPanel {
public Image image;
private JLabel jlImage;
private static JButton jbOk;
private ArrayList<String> comboBoxValues;
private JComboBox routeComboBox = new JComboBox();
//private JComboBox<ArrayList<>>;
private ActionListener actionListener;
public MapView(){
super(new FlowLayout());
setSize(900, 450);
this.add(getRouteComboBox());
jbOk = new JButton("OK");
jbOk.setActionCommand("OK");
ListenerOfActions listener = new ListenerOfActions();
jbOk.addActionListener(listener);
add(jbOk);
} //constructor end
public void setComboBoxValues(ArrayList<String> comboBoxValues) {
this.comboBoxValues = comboBoxValues;
for (String item: comboBoxValues) {
routeComboBox.addItem( item );
}
}
public void setImage(Image image){
this.image = image;
}
public MapView getView(){
jlImage = new JLabel(new ImageIcon(this.image));
add(jlImage);
return this;
}
public void addListenerOfActions(ActionListener listenForAction) {
this.actionListener = listenForAction;
}
public JComboBox getRouteComboBox(){
return routeComboBox;
}
class ListenerOfActions implements ActionListener {
int selected = 0;
@Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if(actionCommand.equals("OK")) {
int selected = getRouteComboBox().getSelectedIndex() + 1;
System.out.println(selected);
System.out.println("print1");
MapController.updateMap(selected);
}
System.out.println("print2");
}
public int getSelected(){
return this.selected;
}
} //class end
} //class end
然后在您的活动中,实现上述接口并覆盖方法:
public interface AddLifecycleCallbackListener {
void addLifeCycleCallBack(YouTubePlayerView youTubePlayerView);
}
最后,在适配器内部,初始化YoutubePlayerView之后,添加以下代码:
public class MainActivity extends AppCompatActivity implements AddLifecycleCallbackListener
//...
@Override
public void addLifeCycleCallBack(YouTubePlayerView youTubePlayerView) {
getLifecycle().addObserver(youTubePlayerView);
}
您将必须将上下文传递给适配器。