AsyncTask的重新执行,而片段之间切换 [英] AsyncTask is re-executing while switching between fragments

查看:173
本文介绍了AsyncTask的重新执行,而片段之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MainActivity.class 从活动延伸。我创建了像结构的标签。在单击任何图像。显示新的片段。我的第一个片段是文章。它有一个的AsyncTask 联想吧。

当我去到另一个片段复出它.asyncTask再次调用。而整个的ListView重建。我只是想禁用的AsyncTask再次调用并保存片段的previous状态。

我有 addToBackStack(空); 同时加入片段。

  getFragmentManager()的BeginTransaction()代替(R.id.container,新的第())addToBackStack(空).commit()。;
 

,其中第一个片段和容器是的FrameLayout 在mainActivity.xml

我想告诉我已关闭的片段。像我们这样的活动通过设置LaunchMode +单人什么的。我不清除backStack。

我只需要像我们这样的TabActivity活动之间进行切换。在 TabActivity 如果我们想重申,我们必须在 onResume指定它的AsyncTask的()。不然也不会叫

文章片段

 公共类文章扩展片段
{
    ListView控件的ListView;

    活动范围内;

    ArrayList的< HashMap的<字符串,字符串>> art_list;

    ArticleAdapter适配器;

    字符串URL =htt​​p://tabletennisdaily.co.uk/webservices/view_articles.php;

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
            捆绑savedInstanceState)
    {
        视图V = inflater.inflate(R.layout.article,集装箱,假);

        上下文= getActivity();

        ListView控件=(ListView控件)V.findViewById(R.id.art_listview);

        新ArticleTask(getActivity(),网址,ListView控件).execute(URL);

        返回伏;
    }
}
 

MainActivity

 公共类MainActivity扩展活动//实现FragmentDelegate,FragmentManager.OnBackStackChangedListener
{
    公众的LinearLayout TAB1,TAB2,TAB3,TAB4;

    公共ImageView的IMG1,IMG2,IMG3,IMG4;

    @覆盖
    保护无效的onCreate(包savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.practicing);

        在里面();
    }

    私人无效的init()
    {
        TAB1 =(的LinearLayout)findViewById(R.id.tab1);

        TAB2 =(的LinearLayout)findViewById(R.id.tab2);

        TAB3 =(的LinearLayout)findViewById(R.id.tab3);

        TAB4 =(的LinearLayout)findViewById(R.id.tab4);

        IMG1 =(ImageView的)findViewById(R.id.tab_img1);

        IMG2 =(ImageView的)findViewById(R.id.tab_img2);

        IMG3 =(ImageView的)findViewById(R.id.tab_img3);

        IMG4 =(ImageView的)findViewById(R.id.tab_img4);

        。getFragmentManager()的BeginTransaction()代替(R.id.container,新的第())addToBackStack(空).commit()。
    }

    公共无效selectFrag(查看视图){

        片段FR = NULL;

        如果(查看== findViewById(R.id.tab1))
        {
            img1.setBackgroundResource(R.drawable.articles_on);

            img2.setBackgroundResource(R.drawable.forum_off);

            img3.setBackgroundResource(R.drawable.video_off);

            img4.setBackgroundResource(R.drawable.profile_off);

            FR =新的第();
        }
        否则,如果(查看== findViewById(R.id.tab2))
        {
            img1.setBackgroundResource(R.drawable.articles_off);

            img2.setBackgroundResource(R.drawable.forum_on);

            img3.setBackgroundResource(R.drawable.video_off);

            img4.setBackgroundResource(R.drawable.profile_off);

            FR =新的论坛();
        }
        否则,如果(查看== findViewById(R.id.tab3))
        {
            img1.setBackgroundResource(R.drawable.articles_off);

            img2.setBackgroundResource(R.drawable.forum_off);

            img3.setBackgroundResource(R.drawable.video_on);

            img4.setBackgroundResource(R.drawable.profile_off);

            FR =新媒体();
        }
        否则,如果(查看== findViewById(R.id.tab4))
        {
            img1.setBackgroundResource(R.drawable.articles_off);

            img2.setBackgroundResource(R.drawable.forum_off);

            img3.setBackgroundResource(R.drawable.video_off);

            img4.setBackgroundResource(R.drawable.profile_on);

            FR =新的配置文件();
        }

        FragmentManager FM = getFragmentManager();

        FragmentTransaction fragmentTransaction = fm.beginTransaction();

        fragmentTransaction.replace(R.id.container,法国);

        fragmentTransaction.addToBackStack(空); // MainActivity.TAG); // addToBackStack(空);

        fragmentTransaction.commit();


    }
}
 

practicing.xml

 < XML版本=1.0编码=UTF-8&GT?;
< RelativeLayout的的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:ID =@ + ID / mainlayout
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>

    <的FrameLayout
        机器人:ID =@ + ID /容器
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
        机器人:layout_above =@ + ID /底部/>

    <的LinearLayout
        机器人:ID =@ + ID /底
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:baselineAligned =假
        机器人:layout_alignParentBottom =真
        机器人:方向=横向>

        <的LinearLayout
            机器人:ID =@ + ID / TAB1
            机器人:layout_width =0dp
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_gravity =中心
            机器人:layout_weight =1
            机器人:的onClick =selectFrag
            机器人:重力=中心
            机器人:方向=垂直>

            < ImageView的
                机器人:ID =@ + ID / tab_img1
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:layout_margin =10dp
                机器人:背景=@可绘制/ articles_on
                机器人:填充=10dp
                机器人:scaleType =中心/>

        < / LinearLayout中>

        <的LinearLayout
            机器人:ID =@ + ID / TAB2
            机器人:layout_width =0dp
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_gravity =中心
            机器人:layout_weight =1
            机器人:的onClick =selectFrag
            机器人:重力=中心
            机器人:方向=垂直>

            < ImageView的
                 机器人:ID =@ + ID / tab_img2
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:layout_margin =10dp
                机器人:背景=@可绘制/ forum_off
                机器人:填充=10dp
                机器人:scaleType =中心/>

        < / LinearLayout中>

        <的LinearLayout
            机器人:ID =@ + ID / TAB3
            机器人:layout_width =0dp
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_gravity =中心
            机器人:layout_weight =1
            机器人:的onClick =selectFrag
            机器人:重力=中心
            机器人:方向=垂直>

            < ImageView的
                 机器人:ID =@ + ID / tab_img3
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:layout_margin =10dp
                机器人:背景=@可绘制/ video_off
                机器人:填充=10dp
                机器人:scaleType =fitXY/>


        < / LinearLayout中>

        <的LinearLayout
            机器人:ID =@ + ID / TAB4
            机器人:layout_width =0dp
            机器人:layout_height =WRAP_CONTENT
            机器人:layout_gravity =中心
            机器人:layout_weight =1
            机器人:的onClick =selectFrag
            机器人:重力=中心
            机器人:方向=垂直>

            < ImageView的
                 机器人:ID =@ + ID / tab_img4
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:layout_margin =10dp
                机器人:背景=@可绘制/ profile_off
                机器人:填充=10dp
                机器人:scaleType =fitXY/>


        < / LinearLayout中>
    < / LinearLayout中>

< / RelativeLayout的>
 

解决方案

什么 addToBackStack()做的是:它增加了该片段交易以它的堆栈,因此它知道,当你preSS回来了,它应该表现出你的第一个片段。因此,T还正是这一点,再次表明你的第一个片段与片段的 onCreatView()再次调用。在这里,你onCreateView,所有初始化发生和的AsyncTask 被调用。这就是为什么它会发生,每次你片段之间进行切换。

我实现了这个问题的解决方案是:

  1)保持鉴于片段作为一个类变量。
2)在onCreateView所有操作()仅当视图为空。
 

所以,你应该改变:

 公共类文章扩展片段
{
    ListView控件的ListView;

    活动范围内;

    ArrayList的< HashMap的<字符串,字符串>> art_list;

    ArticleAdapter适配器;

    字符串URL =htt​​p://tabletennisdaily.co.uk/webservices/view_articles.php;

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
            捆绑savedInstanceState)
    {
        视图V = inflater.inflate(R.layout.article,集装箱,假);

        上下文= getActivity();

        ListView控件=(ListView控件)V.findViewById(R.id.art_listview);

        新ArticleTask(getActivity(),网址,ListView控件).execute(URL);

        返回伏;
    }
}
 

 公共类文章扩展片段
{
    ListView控件的ListView;

    活动范围内;

    ArrayList的< HashMap的<字符串,字符串>> art_list;

    ArticleAdapter适配器;

    字符串URL =htt​​p://tabletennisdaily.co.uk/webservices/view_articles.php;

    视图V; //设置片段观为一个类变量的位置

    @覆盖
    公共查看onCreateView(LayoutInflater充气,容器的ViewGroup,
            捆绑savedInstanceState)
    {//检查片段之前实例化。如果不是,创建新视图
        如果(V == NULL){
            V = inflater.inflate(R.layout.article,集装箱,假);

            上下文= getActivity();

            ListView控件=(ListView控件)V.findViewById(R.id.art_listview);

            新ArticleTask(getActivity(),网址,ListView控件).execute(URL);

        }
        其他{//如果已经实例使用相同的旧V
            ((的ViewGroup)V.getParent())removeView(Ⅴ)。
        }

        返回伏;
    }
}
 

在这里,我们将视图V之外,使之成为类变量。因此,如果它是第一次的片段被调用时,它为空和初始化时,否则它转到别的黑色。 else块是必需的,因为 onCreateView()补充说不管它返回的视图的父母的孩子,所以既然V是已经在那里,我们将其取出并 onCreateView 再次自动添加它。

I have a MainActivity.class which extends from Activity . I created a tab like structure . on clicking any of the image . new fragment is displayed. My first fragment is Article. it has a AsyncTask associate with it.

when i go to another fragment and comeback to it .asyncTask call again. And the whole listView is recreated . I simply want to disable AsyncTask for calling again and save the previous state of the fragment.

I have addToBackStack(null); while adding fragments.

getFragmentManager().beginTransaction().replace(R.id.container, new Article()).addToBackStack(null).commit();

where Article is a fragment and container is the frameLayout in the mainActivity.xml

I want to show the fragment where i left off. Like we do in Activities by setting LaunchMode+"Single" or something . I am not clearing backStack.

I simply need to switch between Activities like we do in TabActivity. in TabActivity if we want to repeat the AsyncTask we have to specify it in onResume(). otherwise it will not called

Article Fragment

public class Article extends Fragment
{
    ListView listView;

    Activity context;

    ArrayList<HashMap<String,String>> art_list;

    ArticleAdapter adapter;

    String url="http://tabletennisdaily.co.uk/webservices/view_articles.php";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        View V = inflater.inflate(R.layout.article, container, false);

        context = getActivity();

        listView = (ListView) V.findViewById(R.id.art_listview);

        new ArticleTask(getActivity(), url, listView).execute(url);

        return V;
    }
}

MainActivity

public class MainActivity extends Activity //implements FragmentDelegate,FragmentManager.OnBackStackChangedListener
{
    public LinearLayout Tab1,Tab2,Tab3,Tab4;

    public ImageView img1,img2,img3,img4;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.practicing);

        init();
    }

    private void init()
    {
        Tab1 = (LinearLayout) findViewById(R.id.tab1);

        Tab2 = (LinearLayout) findViewById(R.id.tab2);

        Tab3 = (LinearLayout) findViewById(R.id.tab3);

        Tab4 = (LinearLayout) findViewById(R.id.tab4);

        img1 = (ImageView)findViewById(R.id.tab_img1);

        img2 = (ImageView)findViewById(R.id.tab_img2);

        img3 = (ImageView)findViewById(R.id.tab_img3);

        img4 = (ImageView)findViewById(R.id.tab_img4); 

        getFragmentManager().beginTransaction().replace(R.id.container, new Article()).addToBackStack(null).commit();   
    }

    public void selectFrag(View view) {

        Fragment fr = null;

        if (view == findViewById(R.id.tab1)) 
        {           
            img1.setBackgroundResource(R.drawable.articles_on);

            img2.setBackgroundResource(R.drawable.forum_off);

            img3.setBackgroundResource(R.drawable.video_off);

            img4.setBackgroundResource(R.drawable.profile_off);

            fr = new Article();
        } 
        else if(view == findViewById(R.id.tab2)) 
        {
            img1.setBackgroundResource(R.drawable.articles_off);

            img2.setBackgroundResource(R.drawable.forum_on);

            img3.setBackgroundResource(R.drawable.video_off);

            img4.setBackgroundResource(R.drawable.profile_off);

            fr = new Forum();
        }
        else if(view == findViewById(R.id.tab3))
        {
            img1.setBackgroundResource(R.drawable.articles_off);

            img2.setBackgroundResource(R.drawable.forum_off);

            img3.setBackgroundResource(R.drawable.video_on);

            img4.setBackgroundResource(R.drawable.profile_off);

            fr = new Medias();
        }
        else if(view == findViewById(R.id.tab4))
        {
            img1.setBackgroundResource(R.drawable.articles_off);

            img2.setBackgroundResource(R.drawable.forum_off);

            img3.setBackgroundResource(R.drawable.video_off);

            img4.setBackgroundResource(R.drawable.profile_on);

            fr = new Profile();
        }

        FragmentManager fm = getFragmentManager();

        FragmentTransaction fragmentTransaction = fm.beginTransaction();

        fragmentTransaction.replace(R.id.container, fr);

        fragmentTransaction.addToBackStack(null);//MainActivity.TAG);//.addToBackStack(null);

        fragmentTransaction.commit();


    }
}

and practicing.xml is

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/bottom" />

    <LinearLayout
        android:id="@+id/bottom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="false"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/tab1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:onClick="selectFrag"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/tab_img1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/articles_on"
                android:padding="10dp"
                android:scaleType="center" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/tab2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:onClick="selectFrag"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                 android:id="@+id/tab_img2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/forum_off"
                android:padding="10dp"
                android:scaleType="center" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/tab3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:onClick="selectFrag"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                 android:id="@+id/tab_img3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/video_off"
                android:padding="10dp"
                android:scaleType="fitXY" />


        </LinearLayout>

        <LinearLayout
            android:id="@+id/tab4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:onClick="selectFrag"
            android:gravity="center"
            android:orientation="vertical" >

            <ImageView
                 android:id="@+id/tab_img4"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:background="@drawable/profile_off"
                android:padding="10dp"
                android:scaleType="fitXY" />


        </LinearLayout>
    </LinearLayout>

</RelativeLayout>

解决方案

What addToBackStack() does is: it adds the fragment transaction to its stack, so it knows that when you press back, it should show your first fragment. So t does exactly that, and shows your first fragment again and the fragment's onCreatView() is called again. Here in your onCreateView, all initialization occurs and the AsyncTask is called. This is why it happens everytime you change between fragments.

The solution I implemented for this problem is:

1) Keep view of fragment as a class variable.
2) Perform all actions in onCreateView() only if the view is null.

So you should change:

public class Article extends Fragment
{
    ListView listView;

    Activity context;

    ArrayList<HashMap<String,String>> art_list;

    ArticleAdapter adapter;

    String url="http://tabletennisdaily.co.uk/webservices/view_articles.php";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        View V = inflater.inflate(R.layout.article, container, false);

        context = getActivity();

        listView = (ListView) V.findViewById(R.id.art_listview);

        new ArticleTask(getActivity(), url, listView).execute(url);

        return V;
    }
}

to:

  public class Article extends Fragment
{   
    ListView listView;

    Activity context;

    ArrayList<HashMap<String,String>> art_list;

    ArticleAdapter adapter;

    String url="http://tabletennisdaily.co.uk/webservices/view_articles.php";

    View V; //SET THE FRAGMENTS VIEW AS A CLASS VARIABLE HERE    

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {   //CHECK IF FRAGMENT IS INSTANTIATED BEFORE. IF IT IS NOT, CREATE NEW VIEW
        if(V == null){ 
            V = inflater.inflate(R.layout.article, container, false);

            context = getActivity();

            listView = (ListView) V.findViewById(R.id.art_listview);

            new ArticleTask(getActivity(), url, listView).execute(url);

        }
        else{ //IF ALREADY INSTANTIATED USE SAME OLD V 
            ((ViewGroup)V.getParent()).removeView(V);
        }

        return V;
    }
}

Here, we move View V outside and make it a class variable. So if it is the first time the fragment is called, it is null and the initialization occurs, otherwise it goes to else black. Else block is required because onCreateView() adds whatever it returns as a child of the view's parent, so since V is already there, we remove it and onCreateView automatically adds it again.

这篇关于AsyncTask的重新执行,而片段之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆