片段事务时冻结UI

Mer*_*ryl 5 android android-fragments android-fragmentactivity fragmenttransaction

我正面临使用FragmentManager替换片段的问题.我的问题是冻结用户界面.我正在努力找到一些好的做法和/或库来处理我的问题.

我的部分代码:

主要活动布局:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<FrameLayout
    android:id="@+id/content"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

</android.support.v4.widget.DrawerLayout>
Run Code Online (Sandbox Code Playgroud)

主要活动类

public class MyActivity extends Activity 
Run Code Online (Sandbox Code Playgroud)

用方法

  public void nextFragment(Fragment fragment, int position) {
    fragment.setArguments(new Bundle());
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager
            .beginTransaction()
            .replace(R.id.content, fragment).commit();

}
Run Code Online (Sandbox Code Playgroud)

我的每个片段都像

import android.app.Fragment;

public class SomeFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    RelativeLayout rootView = (RelativeLayout) inflater.inflate(
            R.layout.fragment_layout, container, false);
    //many long time data downloading & creating view
    }

private void nextFragment() {

        ((MyActivity) getActivity()).nextFragment(
                new SomeNextFragment(), 0);

    }
}
Run Code Online (Sandbox Code Playgroud)

现在因为在每个片段上下载数据,我的UI开始冻结.在此先感谢您的帮助.

Ree*_*eed 2

As a rule, you should not do the long running/blocking operations on the UI thread. Either use a worker thread or an AsyncTask.

Generally, I would suggest that you create whatever you can in onCreateView then set values after the background operation is complete. For example, create a TextView right away, then when you get the result from the background operation, then set the text in the already existing TextView.

To use a thread:

final Handler handler = new Handler();
new Thread(new Runnable(){
    @Override
    public void run(){
       //long running code
       //this is running on a background thread
       final String someText = //result of long running code
       handler.post(new Runnable(){
           @Override
           public void run(){
               //since the handler was created on the UI thread,
               //   this code will run on the UI thread
               someTextView.setText(someText);
           }
       });
    }
}).start();
Run Code Online (Sandbox Code Playgroud)

You can also use getActivity().runOnUiThread(new Runnable(){...}); instead of using Handler