我有一个viewpager。它有3页。从活动开始我必须在片段上按下按钮时播放一些音乐文件。在播放过程中,几个按钮将被隐藏,播放按钮将被显示。所以我使用委托在Activity和Fragment之间进行通信。播放结束后触发委托函数,但始终返回片段号0或2.始终跳过1个片段。所以要么它启用第1页或第3页按钮而不启用第2页。请帮助。
(抱歉我的英语不好)
我的界面:
PlayResult.java
public interface PlayResult {
void PlayCompleted(boolean output);
}
PlayActivity.java
public PlayResult playDelegate = null;
void play()
{
try
{
try {
if(mp != null && mp.isPlaying())
mp.stop();
mp = null;
}
catch (Exception ex){}
mp = MediaPlayer.create(PlayActivity.this, StaticClass.getAudioResourceId(fileName, PlayActivity.this));
mp.start();
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
try {
mp.stop();
mp.release();
}
catch (Exception ex){}
if(playingButton != null)
{
try {
Thread.sleep(1000);
playMusic(dm.audio, dm, null, showButton);
}
catch (Exception ex)
{
//Log.e("error thread", ex.getMessage());
}
}
else
{
playDelegate.PlayCompleted(true);
//showButton();
}
}
});
}
catch (Exception ex){ //Log.e("error playing", ex.getMessage()+ ex.getCause());
}
}
和我的片段
viewpager_fragment.java
PlayActivity playActivity;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate((R.layout.viewpager_layout), container, false);
_context = view.getContext();
imgButton1 = (ImageView) view.findViewById(R.id.imgButton1);
imgButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playMusic(dm.b1audio, dm, imgButton1,imgButton1);
}
});
imgButton2 = (ImageView) view.findViewById(R.id.imgButton2);
imgButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playMusic(dm.b2audio, dm, imgButton2,imgButton2);
}
});
img = (ImageView) view.findViewById(R.id.image);
img.setImageResource(StaticClass.getResourceId(dm.image, _context));
btnMoveForward = (ImageView) view.findViewById(R.id.btnMoveForward);
playActivity = (PlayActivity) getActivity();
playActivity.playDelegate = this;
}
private void showButton()
{
btnMoveBackward.setVisibility(View.VISIBLE);
btnMoveForward.setVisibility(View.VISIBLE);
btnHome.setVisibility(View.VISIBLE);
imgButton1.setVisibility(View.VISIBLE);
imgButton2.setVisibility(View.VISIBLE);
imgButton1.setEnabled(true);
imgButton2.setEnabled(true);
}
void playMusic(String fileName, final DataModel dm , final ImageView playingButton, final ImageView showButton)
{
hideButton(showButton);
playActivity.playMusic(fileName, dm, playingButton, showButton);
}
@Override
public void PlayCompleted(boolean output) {
showButton();
Log.e("Play completed del", "from delegate"+ ", dm "+dm.pageno+ btnHome.getVisibility());
}
答案 0 :(得分:1)
问题是回调应该在您命名委托时的片段中。使用接口对象时,单击时可以在碎片中调用cqn方法,但该方法应该在活动中实现。你差不多了。
答案 1 :(得分:1)
您正在fragment.createView
设置委托
您还使用ViewPager来处理处理其生命周期的片段。因此,每次寻呼机创建新片段时,活动中的代表都会被替换。
View pager and fragment lifecycle
这显示了如何确定当前可见的片段。