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

2023-12-02

活动配置文件.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教程,但它没有像我期望的那样工作。


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

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

每次更改选项卡时选项卡片段都会获取数据 的相关文章

随机推荐

  • 找不到有效的签名身份?

    我已经尝试用 mono 创建一个发行版本已经好几天了 我从我们的 团队代理 那里获得了发行配置文件和发行证书 并分别拖放到 xcode organizer 和 keychain access 上 但是仍然有警告消息显示 在您的钥匙串中找不到
  • Java解压字节数组

    在服务器 C 上 二进制数据使用以下方式压缩ZLib功能 compress2 并将其发送到客户端 Java 在客户端 Java 应使用以下代码片段解压缩数据 public static String unpack byte packedBu
  • SPARQL 中的幂(指数)和其他数学函数支持

    I am trying to write a SPARQL query where I want to filter on the square of something but I am simply unable to figure o
  • 如何使默认 bin 目录在 Eclipse 中可见? [复制]

    这个问题在这里已经有答案了 可能的重复 我该怎么做才能在 eclipse 上显示 bin 文件夹 我知道这是一个searing的重复项this问题 但是该问题中提供的答案对我不起作用或对我没有任何帮助 我正在尝试获取项目的默认输出文件夹 b
  • 更改资源字典中的 SolidColorBrush#Color 失败:属性为只读 [重复]

    这个问题在这里已经有答案了 我有一个SolidColorBrushApp xaml 中的资源如下所示
  • wireshark 如何在同一端口上使用两个 lua 解析器正确解析

    我正在编写lua脚本作为wireshark 1 12 4 插件来剖析我的私有协议 我有两个协议 我为每个协议编写一个lua脚本 两个lua脚本看起来如下 local my pro Proto MyPro My Protocol local
  • 程序从哪里分配内存?

    作为一名 C 和 C 程序员 我使用过malloc and new来分配内存 我只是想知道 操作系统如何分配内存 它是从 RAM 硬盘还是其他地方分配 我可以从硬盘借用内存以防万一吗 它实际上比你想象的要复杂得多 操作系统以 页面 的形式考
  • 如何在recycler视图中访问MainActivity的组件来制作onclick监听器?

    我创建了类似 YouTube 的应用程序 其中包含一个视频视图 顶部 和回收器视图 视频视图下方 我陷入困境 我想在 recyclerview 项目上创建 onclicklistner 并更改视频路径来更改视频 但是如何访问适配器类中的 v
  • PHP 中的 SFTP - 未定义的常量 CURLOPT_PROTOCOLS 和 CURLPROTO_SFTP?

    从我的 php 脚本中 我需要能够通过 sftp 将 csv 文件上传到远程服务器 我遵循了这个问题的公认答案 从 PHP 内部进行 SFTP 这是我的代码的样子
  • 使用公式将 Excel 子集列转换为数组

    我需要将帐号放入一个数组中 该数组在列选择上指示为 1 预期结果是 FD 002 17 FD 004 17 我计划在名称范围中使用它 子集感兴趣的表 我尝试使用 INDEX B2 B6 MATCH 1 A2 A6 1 但这失败了Match不
  • openFileInput() 和/或 openFileOutput() I/O 流默默失败

    我一直在研究 android 平台 研究不同的数据存储方式 现在我正在使用Context方法openFileInput and openFileOutput 正如这两种方法的文档告诉我的那样 我创建了一个名为 default 的文件 这是一
  • 几分钟后服务自动停止

    我正在创建一个服务 当活动处于后台以及整个应用程序被销毁时 该服务应该可以工作 我每隔 1 分钟调用一次服务中的位置坐标 但是 当我尝试这样做时 该服务会在 12 15 分钟后自动关闭 我希望该服务能够无休止地工作 直到并且除非它被用户交互
  • 定制系列化

    我有一些必须序列化的对象 class Displayable string name Sprite icon The icon字段需要自定义序列化 因为Sprites 已经被序列化 在不同的文件中 具有自己的格式 由游戏引擎 我只需要存储一
  • Jquery - 在悬停时添加类

    我想要当鼠标继续运行时lijquery 向元素添加一个类 ul class menu li Menu Item li li Menu Item li li Menu Item li li Menu Item li ul
  • Galaxy Note 5:自动降低密度

    我创建了一个依赖某些屏幕指标来运行的应用程序 它在除 Galaxy Note 5 之外的所有设备上都能正常工作 在 Note 5 上 它报告的屏幕尺寸为 1080x1920 而实际屏幕尺寸为 1440x2560 我还在 logcat 中看到
  • 使用泛型返回文字字符串或来自 Dictionary

    我想这一次我超越了自己 请随意编辑标题 我也想不出一个好的标题 我正在从一个文件中读取内容 然后该文件中将包含一个字符串 因为它就像一个 xml 文件 但文件中将是一个文字值或一个 命令 用于从 workContainer 获取值 so
  • 为什么这个巴特沃斯滤波器在 R 和 Matlab 中呈现不同的结果?

    我试图对 R 中的数据使用 20Hz 低通滤波器 但是当我使用 filtfilt 函数时 该图与 matlab 中的不同 我在 R 中使用以下代码 fc lt 20 fs lt 100 Wn lt pi fc 2 fs testar lt
  • 如何根据滚动位置缩小图像宽度

    我正在寻找基于滚动缩小徽标 到目前为止 我有这样的事情 logoSize function var headerOffset window height 650 var maxScrollDistance 1300 window scrol
  • 多租户Asp.net Core网站中基于参数的JWT认证

    我在 net core 2 1 网站中使用基于 JWT 的身份验证 目前这工作正常 现在 我必须创建一个 API 多租户 并且每个租户都将拥有自己的密钥 租户 ID 将作为参数传递给 API Authorize HttpGet tenant
  • 每次更改选项卡时选项卡片段都会获取数据

    活动配置文件 xml