每次更改选项卡时,选项卡片段都会获取数据

时间:2014-08-16 06:30:06

标签: java android android-fragments android-tabs

activity_profile.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="?android:attr/actionBarSize"
android:background="@drawable/stalker_background" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" 
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

            <android.support.v4.view.ViewPager
                android:id="@+id/VPSlider"
                android:layout_width="match_parent"
                android:layout_height="175dp"
            />


            <android.support.v4.app.FragmentTabHost
                android:id="@android:id/tabhost"
                android:layout_width="match_parent"
                android:layout_height="match_parent" >

                <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" >

                    <TabWidget
                    android:id="@android:id/tabs"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal" />

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

                </LinearLayout>

                </android.support.v4.app.FragmentTabHost>

            </LinearLayout>
            </ScrollView>


</LinearLayout>

ProfileActivity.java

package com.stalker.androidapp;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.Window;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.facebook.Session;
import com.google.gson.Gson;
import com.stalker.adapters.ViewPagerAdapter;
import com.stalker.objects.HomeSliderClassForAdapter;
import com.stalker.objects.LikeCategorySummaryResult;
import com.stalker.objects.StoryResult;
import com.stalker.objects.eStoryType;

public class ProfileActivity extends FragmentActivity {

AsyncTask<String, String, String> StoryResponse;
public String storyResponseString;

TextView tv;
public String UserId;
String UserName;
String AccessToken;
ViewPager VPSlider;
public LikeCategorySummaryResult interestResult;
FragmentTabHost mTabHost;
StoryResult Stories = new StoryResult();

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    VPSlider = (ViewPager) findViewById(R.id.VPSlider);




    // /////////////////////////

    mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup(this, getSupportFragmentManager(),
            android.R.id.tabcontent);
    mTabHost.addTab(
            mTabHost.newTabSpec("tab1").setIndicator(
                    getResources().getString(R.string.interest)),
            InterestTabFragment.class, null);
    mTabHost.addTab(
            mTabHost.newTabSpec("tab2").setIndicator(
                    getResources().getString(R.string.interaction)),
            InteractionTabFragment.class, null);
    mTabHost.addTab(
            mTabHost.newTabSpec("tab3").setIndicator(
                    getResources().getString(R.string.hangout)),
            HangoutTabFragment.class, null);

    mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

        @Override
        public void onTabChanged(String tabId) {
            // TODO Auto-generated method stub
            FragmentManager fragmentManager = getSupportFragmentManager();

            InterestTabFragment tabOneFrgment = (InterestTabFragment) fragmentManager
                    .findFragmentByTag("tab1");

            InteractionTabFragment tabTwoFrgment = (InteractionTabFragment) fragmentManager
                    .findFragmentByTag("tab2");

            HangoutTabFragment tabThreeFrgment = (HangoutTabFragment) fragmentManager
                    .findFragmentByTag("tab3");

            FragmentTransaction fragmentTransaction = fragmentManager
                    .beginTransaction();

            if (tabId.equalsIgnoreCase("tab1")) {
                if (tabOneFrgment != null) {
                    if (tabTwoFrgment != null) {
                        fragmentTransaction.hide(tabTwoFrgment);
                    }
                    if (tabThreeFrgment != null) {
                        fragmentTransaction.hide(tabThreeFrgment);
                    }                       
                    fragmentTransaction.show(tabOneFrgment);
                }
            } else if (tabId.equalsIgnoreCase("tab2")) {
                if (tabTwoFrgment != null) {
                    if (tabOneFrgment != null) {
                        fragmentTransaction.hide(tabOneFrgment);
                    }
                    if (tabThreeFrgment != null) {
                        fragmentTransaction.hide(tabThreeFrgment);
                    }
                    fragmentTransaction.show(tabTwoFrgment);
                }
            } else {
                if (tabThreeFrgment != null) {
                    if (tabOneFrgment != null) {
                        fragmentTransaction.hide(tabOneFrgment);
                    }
                    if (tabTwoFrgment != null) {
                        fragmentTransaction.hide(tabTwoFrgment);
                    }
                    fragmentTransaction.show(tabThreeFrgment);
                }
            }

            fragmentTransaction.commit();

        }
    });


    Session session = Session.getActiveSession();
    if (session != null && session.isOpened()) {
        // Get the user's data
        AccessToken = session.getAccessToken();
        makeStoriesRequest(session);
    }



}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.stalker_profile_menu, menu);
    return true;
}

private void makeStoriesRequest(final Session session) {

    String URL = "http://..../";
    JSONObject UserStory;
    JSONObject ProfileStoryString = new JSONObject();
    StoryResponse = new RequestTask().execute(URL);
    try {
        storyResponseString = StoryResponse.get();
        UserStory = new JSONObject(storyResponseString);
        ProfileStoryString = UserStory.getJSONObject("StoryResult");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        Gson gson = new Gson();
        try {
            // j = new JSONObject(responseString);
            Stories = gson.fromJson(ProfileStoryString.toString(),
                    StoryResult.class);
        } catch (Exception e) {
            Log.i("my", e.getMessage());
            e.printStackTrace();
        }

    } catch (Throwable t) {
        Log.e("My App", "Could not parse malformed JSON: \""
                + storyResponseString + "\"" + t.getMessage());
    }

    ViewPagerAdapter adapter = new ViewPagerAdapter(this, getSlider());

    VPSlider.setAdapter(adapter);

}


@Override
protected void onResumeFragments() {
    super.onResumeFragments();

}


}

我有这个片段活动,我正在显示标签。我有三个标签。现在我只在InterestTabFragment.java中添加了代码

package com.stalker.androidapp;

import java.util.concurrent.ExecutionException;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.devsmart.android.ui.HorizontalListView;
import com.facebook.Session;
import com.google.gson.Gson;
import com.stalker.adapters.CategoryLVAdapter;
import com.stalker.objects.LikeCategorySummaryResult;

public class InterestTabFragment extends Fragment{

View view;
String access_token;

AsyncTask<String, String, String> FirstResponse;
public String responseString;
JSONObject joiningYear;
HorizontalListView listview;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreateView(inflater, container, savedInstanceState);
    view = inflater.inflate(R.layout.interest_tab_fragment, container, false);

    listview = (HorizontalListView) view.findViewById(R.id.LVCategory);


        Session session = Session.getActiveSession();
        if (session != null && session.isOpened()) {
            // Get the user's data
            access_token = session.getAccessToken();
            makeInterestRequest(session);
        }

    return view;
}


private void makeInterestRequest(final Session session) {
    access_token = session.getAccessToken();
    String URL =     "http://...";


    JSONObject HomeCardString = new JSONObject();
    FirstResponse = new RequestTask().execute(URL);
    try {
        responseString = FirstResponse.get();
        joiningYear = new JSONObject(responseString);
        HomeCardString = joiningYear.getJSONObject("LikeCategorySummaryResult");
//          HomeCardString = TestApiResult.getJSONObject("UserHomeResult");         
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {       
        Gson gson = new Gson();
        try
        {
//              j = new JSONObject(responseString);
            ((ProfileActivity)getActivity()).interestResult =     gson.fromJson(HomeCardString.toString(), LikeCategorySummaryResult.class);

        }
        catch(Exception e)
        {
            Log.i("myyyy", e.getMessage());
            e.printStackTrace();
        }

    } catch (Throwable t) {
        Log.e("My App", "Could not parse malformed JSON: \"" + responseString + "\"" +    t.getMessage());
    }

    CategoryLVAdapter adapter = new CategoryLVAdapter(getActivity(), R.layout.category_item_template,     ((ProfileActivity)getActivity()).interestResult.categories);

    listview.setAdapter(adapter);

//      listView.setAdapter(adapter);

}


}

此代码可以正常工作。但是当我转到我的第二个标签然后返回第一个标签。它再次加载数据。但我希望它只显示以前的片段不再加载它。

链接到一个很好的教程也会有所帮助,但我已经在关注this教程,但它没有工作,因为我期望它能够正常工作。

1 个答案:

答案 0 :(得分:1)

如果你转到第3个标签然后转到第2个或第1个标签,则会重新创建第1个并调用onCreate,这是片段的默认行为。但是转到第二个选项卡然后返回第一个选项卡将不会重新创建第一个选项卡。我仅在onCreate中对 InterestTabFragment.java 进行了一些更改。看看是否有帮助,如果没有,请通知我,我可以再试一次。感谢.....

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreateView(inflater, container, savedInstanceState);
    view = inflater.inflate(R.layout.interest_tab_fragment, container, false);

    listview = (HorizontalListView) view.findViewById(R.id.LVCategory);

        if(((ProfileActivity)getActivity()).interestResult.categories == null){
            Session session = Session.getActiveSession();
            if (session != null && session.isOpened()) {
                // Get the user's data
                access_token = session.getAccessToken();
                makeInterestRequest(session);
        }
        } else {
            CategoryLVAdapter adapter = new CategoryLVAdapter(getActivity(), R.layout.category_item_template,     ((ProfileActivity)getActivity()).interestResult.categories);

            listview.setAdapter(adapter);
        }


    return view;
}