在FragmentTransaction.commit()之后使片段内的AsyncTask运行

时间:2013-03-10 21:35:16

标签: android android-asynctask android-fragments

我在活动中有FragmentTransaction,我希望AsyncTask在fragmentTransaction.commit()之后的片段中运行。如何在AsyncTask之后运行commit?因为AsyncTask在提交之前和之后运行了2次。有人可以帮忙吗?

*注意:AsyncTask使用FragmentTransaction

发送的活动的String运行


活动:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menudisplay);
        Bundle extras = getIntent().getExtras();
        language = extras.getString("language");
        lang_id = extras.getInt("id");

        MyListFragment mylist = new MyListFragment();


        FragmentTransaction fragmentTrans = getFragmentManager()
                .beginTransaction();

        mylist.language = language;
        fragmentTrans.add(mylist, "language");

        fragmentTrans.commit();
        Log.d("tes", "data loaded");

    }

片段:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_menulist_overview, container,
                false);
            System.out.println("tes="+language+" sama ini = "+asdf);
        onActivityCreated(inflater, container, savedInstanceState);


        return view;

    }
    public void onActivityCreated(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        run();

    }

    public void run(){
        Log.d("Test","How many called?");
        if(language != null)
        new loadcat().execute();

    }

2 个答案:

答案 0 :(得分:1)

我没有收到您编写的注释,但是您可以通过在执行所需的片段内部创建公共方法来简单地AsyncTask事务后运行.commit() {{1}并在代码中的所需位置从AsyncTask调用它。

例如,如果您在Activity

中创建此方法
Fragment

在Activity中,您可以调用此方法:

public void executeAsyncTask(String language, int lang_id)
{
     ...
     asyncTask.execute(language, lang_id);
}

答案 1 :(得分:0)

据我所知,commit执行回调未公开(或者甚至可能不存在)。

所以问题是 - 你想什么时候执行你的AsyncTask

如果您希望在片段创建时执行一次,那么您的代码是正确的,除非您应该从onActivityCreated()中删除明确的onCreateView来电,如下所示:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_menulist_overview, container,
            false);
        System.out.println("tes="+language+" sama ini = "+asdf);
    onActivityCreated(inflater, container, savedInstanceState); // REMOVE THIS LINE


    return view;

}

onActivityCreated是一个回调。明确调用它会导致双重执行任务