活动和片段之间的Android通信
我有一个活动和片段之间的Android通信,android,android-fragments,android-viewpager,Android,Android Fragments,Android Viewpager,我有一个活动,其中包含一个ViewPager。ViewPager的适配器是FragmentStatePagerAdapter。每个页面都是片段。片段包含许多线程。我的问题是,当ViewPager的页面更改时,我必须停止片段内的所有线程。我如何才能做到这一点?您已经询问了有关使用界面实现的活动和片段之间的通信: 你的片段: public class YourFragment extends Fragment{ private OnListener listener; public i
活动
,其中包含一个ViewPager
。ViewPager的适配器
是FragmentStatePagerAdapter
。每个页面都是片段
。片段
包含许多线程。我的问题是,当ViewPager的
页面更改时,我必须停止片段内的所有线程。我如何才能做到这一点?您已经询问了有关使用界面实现的活动和片段之间的通信:
你的片段:
public class YourFragment
extends Fragment{
private OnListener listener;
public interface OnListener
{
void onChange();
}
void initialize( OnListener listener)
{
this.listener = listener;
}
//onview pager change call your interface method that will go to the activity as it has the listener for interface.
listener.onChange();
}
public class yourActivity
extends Activity
implements yourFragment.OnListener
{
// intialize the method of fragment to set listener for interface where you define fragment.
yourFragment.initialize( this );
// implement what you want to do in interface method.
@Override
public void onChange()
{
// implement what you want to do
}
}
您的活动:
public class YourFragment
extends Fragment{
private OnListener listener;
public interface OnListener
{
void onChange();
}
void initialize( OnListener listener)
{
this.listener = listener;
}
//onview pager change call your interface method that will go to the activity as it has the listener for interface.
listener.onChange();
}
public class yourActivity
extends Activity
implements yourFragment.OnListener
{
// intialize the method of fragment to set listener for interface where you define fragment.
yourFragment.initialize( this );
// implement what you want to do in interface method.
@Override
public void onChange()
{
// implement what you want to do
}
}
希望它能有所帮助。Android的应用哲学是杀掉进程,所以也许遵循同样的想法你可以杀掉你的线程。请注意,如果线程拥有锁或监视器,则这可能导致死锁。
对我来说,更严肃的方法似乎是在活动中使用Thread.interrupt()。然后,片段中的线程必须检查Thread.interrupted是否有中断,如果它们被中断,则必须优雅地完成。
如果需要一些同步行为,可以使用Thread.join()
此外,您可以等待一定时间,让线程使用计时器正常完成,然后在超时时杀死它们。
请看一看
为了让这更容易实现,您可以使用java.util.concurrent包的一个或其他助手。简而言之,当用户看不到片段时,该片段应该停止所有线程。对吗?每个片段必须使用setImageBitmap设置许多imageview的图像。它可能导致outofmemory异常。因此,如果页面发生更改,我必须停止线程。我的ViewPager位于活动中。所以我必须在片段中实现这个函数。这个答案应该被标记为答案,这是我发现的最好的答案之一。