仅在选中时加载片段的数据

时间:2014-09-19 12:14:31

标签: android fragment

在我的Androidapp中,我现在使用Swipe View作为我的导航。 如果我启动我的应用程序,这个加载我的所有不同的片段,而不仅仅选择了这一个。如果我在片段之间切换,则视图不会重新加载。 我怎么能这样做只加载选择的视图,如果我切换到一个片段,这将再次重新加载。 谢谢 MainActivity:

public class MainActivity extends FragmentActivity implements ActionBar.TabListener {


AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());


    final ActionBar actionBar = getActionBar();


    assert actionBar != null;
    actionBar.setHomeButtonEnabled(false);

    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mAppSectionsPagerAdapter);
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }
    });


    for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
        actionBar.addTab(
                actionBar.newTab()
                        .setText(mAppSectionsPagerAdapter.getPageTitle(i))
                        .setTabListener(this));
    }
}

@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}




public class AppSectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int i) {
        switch (i) {
            case 0:
                return new EventCalendarFragment();

            default:

                return new VideoListFragment();
        }
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        if (position == 0) {
            return "Event";
        } else  {
            return "Videos";
        }
    }
}

VideoListFragment:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_videos_table, container, false);
    //load customBanner
    imageView = (ImageView) rootView.findViewById(R.id.video_imageView);
    imageView.setVisibility(View.GONE);
    new AsyncTaskParseJson().execute();
    inputSearch = (EditText) rootView.findViewById(R.id.video_inputSearch);
    new UpdateData().execute();


    return rootView;
}
 @Override
    public void setUserVisibleHint(boolean isVisibleToUser){
        if (isVisibleToUser == true){
            new AsyncTaskParseJson().execute();
            new UpdateData().execute();
        }
    }

的UpdateData:

class UpdateData extends AsyncTask<Void, Void, JSONArray> {
    int error = 0;
    InputStream is = null;
    String result = "";
    JSONArray jArray = null;

    ProgressDialog pd;

    @Override
    protected void onPostExecute(JSONArray result) {
        super.onPostExecute(result);
        pd.dismiss();       
    }

    @Override
    protected void onPreExecute() {

        super.onPreExecute();
        pd = ProgressDialog.show(getActivity(), "",
                "Loading...", true);
    }


    @Override
    protected JSONArray doInBackground(Void... arg0) {

        error = 0;
            url = "************";

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
            error = 1;
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
            is.close();
            result = sb.toString();


        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
            error = 1;

        }

        deptList.clear();
        try {
            JSONArray array = new JSONArray(result);
            for (int i = 0; i < array.length(); i++) {
                JSONObject j = array.getJSONObject(i);
                EventCalendarStrings d = new EventCalendarStrings();
                d.name = j.optString("name", "");
                    deptList.add(d);

            }

        } catch (JSONException e) {
            Log.e("log_tag", "No connection " + e.toString());
            error = 1;
        }
        return jArray;
    }
}

Logcat:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException

3 个答案:

答案 0 :(得分:2)

如果我正确理解了您的问题,您应该覆盖片段中的setUserVisibleHint(boolean isVisibleToUser)方法,并将其用作指示您的片段当前可见(如果isVisibleToUser为真)。然后你应该移动你的逻辑(我想它现在在onCreateView中),只有当一个片段当前在屏幕上时才应该调用它。

答案 1 :(得分:0)

Viewpager读取加载的...聪明的

覆盖此方法。

public int getItemPosition (Object object) 
{ 
return POSITION_NONE; 
}

POSITION_NONE:数据已更改,请删除片段。 POSITION_UNCHANGED:数据不变。

答案 2 :(得分:0)

我可能会参加聚会,但这是我的解决方案,它按预期工作。此解决方案还可以防止用户一次又一次地重新发送请求(如果您正在进行网络操作)。

在您的所有子片段中创建一个boolean变量:

private boolean loadFragmentExecuted = false;
子片段中的

创建一个名为loadFragment的通用方法,并将您在onCreateView中添加的所有逻辑移动到该方法:

public void loadFragment()
{
    if(!loadFragmentExecuted)
    {
        //Add your logic to manipulate the UI or load data etc...
        loadFragmentExecuted = true;
    }
}
在您的网页浏览逻辑中,

动态创建片段,如:

//add the fragment
String fragmentName = "com.something." + fragmentId;

//check if the class exists
try
{
    Class myFragmentClass = Class.forName(fragmentName);
    Fragment myFragment = (Fragment) myFragmentClass.newInstance();
    mFragments.add(myFragment);
}
catch (ClassNotFoundException e)
{
    e.printStackTrace();
}
catch (IllegalAccessException e)
{
    e.printStackTrace();
}
catch (InstantiationException e)
{
    e.printStackTrace();
}

然后设置你的寻呼机适配器并附上一个tablayout:

//set our pager adapter that contains different fragments
mPagerAdapter = new BasePagerAdapter(mFragmentManager, mFragments);

//link the adapter to the viewpager
mViewPager.setAdapter(mPagerAdapter);

//cache fragments
int limit = (mPagerAdapter.getCount() > 0 ? mPagerAdapter.getCount() : 1);
mViewPager.setOffscreenPageLimit(limit);

//add the page listner to the viewPager and link it to the tabLayout
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

//on tab selected select current viewpager item
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
    @Override
    public void onTabSelected(TabLayout.Tab tab)
    {
        mViewPager.setCurrentItem(tab.getPosition());

        //get fragment for the selected tab
        Fragment f = mPagerAdapter.getItem(tab.getPosition());

        //load the content of the fragment
        try
        {
            Class c = f.getClass();
            Method loadFragment = c.getMethod("loadFragment");
            loadFragment.invoke(f);
        }
        catch (IllegalAccessException e){}
        catch (InvocationTargetException e){}
        catch (NoSuchMethodException e){}
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab)
    {
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab)
    {
    }
});