我有一个片段,并且为了与父活动进行通信(参见下一个代码块),我使用了一个接口。我包括一个基本的例子,但问题是当我从Spotify OnPlaybackEvent调用函数updateTextView()时我的TextView没有更新活动,如果我通过点击它工作的按钮调用这个相同的函数。我尝试使用Handlers和runonuithread,但似乎没有任何效果。
这是我的片段:
public class PlayerFragment extends Fragment implements SpotifyPlayer.NotificationCallback, ConnectionStateCallback {
public ImageView playButton;
public TrackOperations trackOperationsCallback;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.player_fragment, container, false);
playButton = (ImageView) rootView.findViewById(R.id.playButton);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//THIS WORKS!
trackOperationsCallback.updateTextView();
}
});
return rootView;
}
@Override
public void onPlaybackEvent(PlayerEvent playerEvent) {
if(playerEvent.equals(kSpPlaybackNotifyTrackDelivered)){
//THIS IS PRINTED WHEN A SONG ENDS
Log.d(spoty.TAG, "Player: Event " + playerEvent);
//BUT THIS DONT WORK
trackOperationsCallback.updateTextView();
}
}
public interface TrackOperations {
public void updateTextView();
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
trackOperationsCallback = (TrackOperations) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement TrackOperations");
}
}
}
这是我的父母活动:
public class QueueActivity extends Activity implements PlayerFragment.TrackOperations {
private TextView queueSong;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
queueSong = (TextView) findViewById(R.id.queueSong);
}
@Override
public void updateTextView(){
//THIS IS PRINTED IN BOTH CASES
Log.d(spoty.TAG, "Called!");
//THIS WORKS IF IS CALLED FROM THE BUTTON CLICK OF THE FRAGMENT
//BUT DONT WORK WHEN CALLED FROM THE EVENT IN FRAGMENT
queueSong.setText("ANY RANDOM TEXT");
}
}
我有几天在努力,所以任何建议都将受到高度赞赏。提前谢谢。
答案 0 :(得分:1)
这可能不是最好的方法,但每当我遇到数据传输问题时,我都会使用SharedPreferences解决它,包括Fragment to Fragment通信。这肯定会解决您的问题