java - 每次我更改标签时标签 fragment 获取数据

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

}


}

我有一个正在显示标签的 fragment Activity 。我有三个标签。现在我只在 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);

}


}

这段代码工作正常。但是当我转到第二个选项卡然后返回到第一个选项卡时。它再次加载数据。但我希望它只显示之前的 fragment ,不要再次加载它。

链接到一个很好的教程也会有帮助,但我已经在关注 this教程,但它没有像我期望的那样工作。

最佳答案

如果您转到第 3 个选项卡,然后转到第 2 个或第 1 个选项卡,那么将重新创建第 1 个选项卡并调用 onCreate,这是 fragment 的默认行为。但是只转到第二个选项卡然后返回第一个选项卡不会重新创建第一个选项卡。我仅在 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;
}

关于java - 每次我更改标签时标签 fragment 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25337570/

相关文章:

java - String.valueOf() 的实习

java - 搜索查询并在 jtable 中显示结果

java - Android调用带有外部参数的onClickListener内部方法

Android动态TextView位置

android - 访问改造服务器请求和响应时间 Android

java - Apache POI 版本 3.8 是否有助于解决 "org.apache.poi.poifs.filesystem.OfficeXmlFileException"问题?

android - 无法使用 BuildConfig 访问 API key

java - 无尽的 ViewPager(不循环)

android - 共享元素过渡 imageview 变白

java - 当按下后退按钮时,为Android Fragment调用Java中的AlertDialog.Builder