2015-07-28 3 views
0

Я хотел бы создать ViewPager с 2 элементами, и каждый из его представлений содержит listview. когда я перебираю с одной страницы на другую, каждый раз, когда listview получает обновление. Мне нужно обновить только один раз. Означает, что если один раз загрузить значения для представления списка, тогда я прокручиваю на следующую страницу, которую не нужно перезагружать снова. Мне нужно, чтобы показать уже загрузить значения Просмотреть списокListview внутри viewpager с значениями перезагрузки

код

public class ViewpagerAdapter extends FragmentPagerAdapter { 
private Context _context; 
public static int totalPage=2; 

public ViewpagerAdapter(Context applicationContext, 
     android.support.v4.app.FragmentManager fragmentManager) { 
    super(fragmentManager); 
    _context=applicationContext; 
} 

@Override 
public Fragment getItem(int position) { 
    Fragment f = new Fragment(); 
    switch(position){ 
    case 0: 
     f= FirstFragment.newInstance(_context); 
     break; 
    case 1: 
     f= SecondFragment.newInstance(_context); 
     break; 
    } 
    return f; 
} 
@Override 
public int getCount() { 
    return totalPage; 
}} 

FirstFragment

public class FirstFragment extends Fragment { 


private Context context; 
private List<Historyitem> historyitems; 
HistoryRecycleListAdapter historyadapter; 
Handler mHandler; 

ListView hisrecyclerview; 

public static Fragment newInstance(Context context) { 
    FirstFragment f = new FirstFragment(); 
    return f; 
} 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    ViewGroup view = (ViewGroup) inflater.inflate(R.layout.firstfragment, null); 

    context = getActivity(); 
    hisrecyclerview = (ListView)view.findViewById(R.id.hisrecyclerview); 
    LoadHistoryInitiate();  
    return view; 
} 

public void LoadHistoryInitiate() throws IllegalStateException{ 

    new AsyncTask<String, String, String>(){ 

     protected void onPreExecute() { 

      historyitems = new ArrayList<Historyitem>(); 
      historyitems.clear(); 
     }; 
     @Override 
     protected String doInBackground(String... arg0) { 


       final List<NameValuePair> list=new ArrayList<NameValuePair>(); 
       list.add(new BasicNameValuePair("id", id)); 

       final HttpParams httpParams = new BasicHttpParams(); 
       HttpConnectionParams.setConnectionTimeout(httpParams, 30000); 
       DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); 
       try { 
        httpPost.setEntity(new UrlEncodedFormEntity(list)); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       try { 
        HttpResponse response = httpClient.execute(httpPost); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
        String json = reader.readLine(); 


        JSONObject jsonObj = new JSONObject(json); 
        if(jsonObj.has("values")){ 

         JSONArray feedArray = jsonObj.getJSONArray("values"); 
         for (int i = 0; i < feedArray.length(); i++) { 
          JSONObject feedObj = (JSONObject) feedArray.get(i); 

          final Historyitem item = new Historyitem(); 

          if(feedObj.has("Reported_Time")){ 
           if(!feedObj.getString("Reported_Time").replaceAll(" ", "").equals("")){ 
            item.setReported_Time(feedObj.getString("Reported_Time")); 
           } 
          } 
          historyitems.add(item); 

         } 
        }else{ 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 

       } catch(NullPointerException e){ 
        e.printStackTrace(); 

       } catch (SocketException e) { 
        e.printStackTrace(); 

       } catch (IOException e) { 
        e.printStackTrace(); 

       } 

      return null; 
     } 
     protected void onPostExecute(String result) { 
      System.out.println(historyitems.size()); 
      new Handler().postDelayed(new Runnable() { 

       @Override 
       public void run() { 

         historyadapter = new HistoryRecycleListAdapter(getActivity(), getActivity(),historyitems); 
         hisrecyclerview.setAdapter(historyadapter); 
         hisrecyclerview.addFooterView(btnLoadMore); 
         hisrecyclerview.setAdapter(historyadapter); 
             } 
      }, 1000); 
     }; 
    }.execute(); 
} } 

Второй фрагмент

public class SecondFragment extends Fragment { 
private Context context; 
private List<Loaditem> loaditems; 
RecycleListAdapter loadadapter; 
Handler mHandler; 

ListView recyclerview; 

public static Fragment newInstance(Context context) { 
    SecondFragment f = new SecondFragment(); 
    return f; 
} 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    ViewGroup view = (ViewGroup) inflater.inflate(R.layout.secondfragment, null); 

    context = getActivity(); 
    recyclerview = (ListView)view.findViewById(R.id.recyclerview); 
    LoadInitiate();  
    return view; 
} 

public void LoadInitiate() throws IllegalStateException{ 

    new AsyncTask<String, String, String>(){ 

     protected void onPreExecute() { 

      loaditems = new ArrayList<Loaditem>(); 
      loaditems.clear(); 
     }; 
     @Override 
     protected String doInBackground(String... arg0) { 


       final List<NameValuePair> list=new ArrayList<NameValuePair>(); 
       list.add(new BasicNameValuePair("uid", uid)); 

       final HttpParams httpParams = new BasicHttpParams(); 
       HttpConnectionParams.setConnectionTimeout(httpParams, 30000); 
       DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); 
       try { 
        httpPost.setEntity(new UrlEncodedFormEntity(list)); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       try { 
        HttpResponse response = httpClient.execute(httpPost); 

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
        String json = reader.readLine(); 


        JSONObject jsonObj = new JSONObject(json); 
        if(jsonObj.has("values")){ 

         JSONArray feedArray = jsonObj.getJSONArray("values"); 
         for (int i = 0; i < feedArray.length(); i++) { 
          JSONObject feedObj = (JSONObject) feedArray.get(i); 

          final Loaditem item = new Loaditem(); 

          if(feedObj.has("Time")){ 
           if(!feedObj.getString("Time").replaceAll(" ", "").equals("")){ 
            item.setReported_Time(feedObj.getString("Time")); 
           } 
          } 
          loaditems.add(item); 

         } 
        }else{ 
        } 
       } catch (JSONException e) { 
        e.printStackTrace(); 

       } catch(NullPointerException e){ 
        e.printStackTrace(); 

       } catch (SocketException e) { 
        e.printStackTrace(); 

       } catch (IOException e) { 
        e.printStackTrace(); 

       } 

      return null; 
     } 
     protected void onPostExecute(String result) { 
      System.out.println(historyitems.size()); 
      new Handler().postDelayed(new Runnable() { 

       @Override 
       public void run() { 

         loadadapter = new RecycleListAdapter(getActivity(), getActivity(),loaditems); 
         recyclerview.addFooterView(btnLoadMore); 
         recyclerview.setAdapter(loadadapter); 
             } 
      }, 1000); 
     }; 
    }.execute(); 
} } 

ответ

0

самым простым решением было бы setOffscreenPageLimit(int limit) установить его на свой ViewPager ,

+0

когда я красть каждый раз, когда его список перезарядки вида values.I необходимость загружать только один раз. – Arya

+0

, вызывая этот viewPager.setOffscreenPageLimit (2); он гарантирует *, что фрагменты не будут называть их onCreateView еще раз, если вы тоже решили. – k0sh

0

Чтобы решить проблему, используйте ниже метод внутри Активность:

setOffscreenPageLimit(int limit) 

Set the number of pages that should be retained to either side of the current page in the view hierarchy in an idle state. 

Добавить ниже линии после ViewPager конкретизации

viewpager.setOffscreenPageLimit(2) 
Смежные вопросы