标签片段获取数据我每次更改选项卡时 [英] Tabs fragment fetch data every time I change tab

查看:168
本文介绍了标签片段获取数据我每次更改选项卡时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

activity_profile.xml

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

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();

}


}

我有哪些我展示标签该片段的活性。我有三个标签。现在我只加code里面InterestTabFragment.java

I have this fragment activity on which I'm showing tabs. I have three tabs. For now I have only added code inside 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);

}


}

这code工程确定。但是,当我转到我的第二个选项卡,然后返回到第一个标签。它再次加载数据。但我希望它只是显示previous片段不要再次加载它。

This code works ok. But when I goto my second tab and then return to first tab. It load data again. but I want it to just show previous fragment don't load it again.

链接到一个不错的教程也将是有益的,但​​我已经下的本教程的,但它不工作,我期待它的工作。

Link to a nice tutorial will also be helpful, but I am already following this tutorial but it is not working as I was expecting it to work.

推荐答案

如果你去第三个标签,然后转到第二或第一个选项卡,然后第一次将被重新创建并调用的onCreate,这是片段的默认行为。但要仅仅第2选项卡,然后返回到第一个选项卡将不会重新创建第一个标签。我在下面的onCreate只发在 InterestTabFragment.java 的一些变化。看看是否有帮助,如果没有则通知我,我可能会尝试一次。谢谢.....

If you go to 3rd tab then go to the 2nd or 1st tab then 1st will be recreated and call onCreate, that is the default behavior of fragment. But going to just 2nd tab and then back to 1st tab will not recreate the 1st tab. I have made some changes in the InterestTabFragment.java below only in onCreate. See if it helps, if not then notify me, I may try again. Thanks.....

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;
}

这篇关于标签片段获取数据我每次更改选项卡时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆