ViewPager:刷新用户滑动的片段视图

时间:2016-10-02 11:46:23

标签: java android android-fragments android-viewpager

我有MainActivity使用viewPager并在用户滑动手势上实例化两个fragment次观看。其中一个片段从服务器获取一些数据并更新其视图。

问题:

在没有互联网连接的情况下启动应用程序,fragment使用某些虚拟数据进行更新,但在应用程序运行时切换Wi-Fi并刷到该片段时,不会使用接收到的数据更新片段

请建议fragment视图在实例化后如何更新。

MainActivity.java

public class MainActivity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
         switch (position) {
            case 0:
                return fragment1.newInstance();
            case 1:
                return fragment3.newInstance();
            default:
                return fragment1.newInstance();
        }
    }

    @Override
    public int getCount() {
      // Show 2 total pages.
       return 2; 
    }
}

FragmentA类(代码中的Fragment3)如下:

public class fragment3 extends Fragment implements YourFragmentInterface{

    public static ListView mylistView;
    public static ConfessionsAdapter adapter;
    public static ArrayList<Confession> confessionList;

    public static Context context;

    public static fragment3 newInstance() {

        fragment3 fragment = new fragment3();

        new HttpGetReq().execute("http://example.com");

        return fragment;
    }

    public fragment3() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        context = getActivity(); // Getting context to tell async task about it, so it can SET stuff here.

        if (container == null) {
            return null;
        }
        View view = inflater.inflate(R.layout.list_fragment, container, false);
        mylistView = (ListView) view.findViewById(android.R.id.list);

        new HttpGetReq().execute("http://example.com");

        return view;
    }
}

HttpGetReq类是AsyncTask,它从服务器获取数据,解析JSON并在list方法中更新fragmentA的doInBackground(),然后将适配器设置为fragmentA的在View方法中列出onPostExecute()

1 个答案:

答案 0 :(得分:1)

首先创建一个检查互联网连接的方法。对我来说,我创建了一个名为Utils的类,在该类中有一个方法,如果有互联网可用,它将返回true

public class Utils {

    public static boolean isNetworkAvailable(Context context) {
        try {
            ConnectivityManager cm = (ConnectivityManager)
                    context.getSystemService(context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = cm.getActiveNetworkInfo();
            // if no network is available networkInfo will be null
            // otherwise check if we are connected
            if (networkInfo != null && networkInfo.isConnected()) {
                return true;
            }
            return false;
        } catch (Exception ex) {
            return false;
        }
    }

}

现在创建一个Broadcast Receiver,当互联网连接状态发生变化时会通知您。如果将其更改为可用的互联网,则会通过本地broadcast manager

发送广播

这是广播接收器的代码,

public class NetworkChangedReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (Utils.isNetworkAvailable(context))
        {
            //sending local broadcast
            Intent i = new Intent("net_connected");
            i.putExtra("message", true);
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);

        }
    }
}

并在manifest注册您的接收器

  <receiver android:name=".NetworkChangedReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
  </receiver>

然后在您的活动中注册您的本地广播接收器,您应该在onResume中进行注册并在onPause中取消注册

 @Override
    public void onResume() {
        super.onResume();

        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
                new IntentFilter("custom-event-name"));
    }

    @Override
    public void onPause() {
        super.onPause();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
    }

并以片段

编写本地广播接收器的功能
   private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                boolean isConnectTed = intent.getBooleanExtra("net_connected",false);
                if(isConnectTed){
                 //if connected then notify to the 
                 mSectionsPagerAdapter.notifyDataSetChanged();
                }
            }
        };