从另一个 Fragment 更新 ViewPager 中的 TextView

2024-01-01

我正在尝试单击另一个片段上的按钮来更新片段中的 TextView。

实际上,我对 Activity 实现了回调函数,并且它确实有效,因为 Logcat 报告 TextView 中的文本已更改。问题是第一个片段中显示的 Textview 没有更新为新值!就像 Fragment 需要更新什么的......

这是 ActionBarTabsPager 活动代码:

import java.util.ArrayList;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ActionBar.Tab;
import android.support.v4.app.SupportActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;

/**
 * Demonstrates combining the action bar with a ViewPager to implement a tab UI
 * that switches between tabs and also allows the user to perform horizontal
 * flicks to move between the tabs.
 */
public class ActionBarTabsPager extends FragmentActivity implements SecondFragment.OnButtonClickedXListener{
    ViewPager  mViewPager;
    TabsAdapter mTabsAdapter;
    FragmentManager fm;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.actionbar_tabs_pager);



        if (savedInstanceState == null) {
             Fragment newFragment = new FirstFragment();
             FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
             ft.add(R.id.abs__custom, newFragment, "FirstFragment").commit();

             Fragment newFragment2 = new FirstFragment();
             FragmentTransaction ft2 = getSupportFragmentManager().beginTransaction();
             ft2.add(R.id.abs__custom, newFragment2, "SecondFragment").commit();
        }
        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab tab1 = getSupportActionBar().newTab().setText("Fragment 1");
        ActionBar.Tab tab2 = getSupportActionBar().newTab().setText("Fragment 2");
        //ActionBar.Tab tab3 = getSupportActionBar().newTab().setText("Fragment 1");
        //ActionBar.Tab tab4 = getSupportActionBar().newTab().setText("Fragment 2");

        mViewPager = (ViewPager)findViewById(R.id.pager);
        mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), mViewPager);

            mTabsAdapter.addTab(tab1, FirstFragment.class);
            mTabsAdapter.addTab(tab2, SecondFragment.class);//LoaderCursorSupport.CursorLoaderListFragment.class);
            //mTabsAdapter.addTab(tab3, FirstFragment.class);//LoaderCustomSupport.AppListFragment.class);
            //mTabsAdapter.addTab(tab4, SecondFragment.class);//LoaderThrottleSupport.ThrottledLoaderListFragment.class);


        if (savedInstanceState != null) {
            getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt("index"));
        }



    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("index", getSupportActionBar().getSelectedNavigationIndex());
    }

    /**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between pages.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct paged in the ViewPager whenever the selected
     * tab changes.
     */
    public class TabsAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
        private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<String> mTabs = new ArrayList<String>();

        public TabsAdapter(FragmentActivity activity, ActionBar actionBar, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mActionBar = actionBar;
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(ActionBar.Tab tab, Class<?> clss) {
            mTabs.add(clss.getName());
            mActionBar.addTab(tab.setTabListener(this));
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Fragment getItem(int position) {
            return Fragment.instantiate(mContext, mTabs.get(position), null);
        }


        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

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

        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        }
    }

    @Override
    public void OnButtonClickedX(View v) {

        if (v==findViewById(R.id.button1)){
            Log.i("TRIGGERED","TRIGGERED");

            FirstFragment ff = (FirstFragment) getSupportFragmentManager().findFragmentByTag("FirstFragment");

            View root = ff.getView();
            TextView tv = (TextView) root.findViewById(R.id.textView1);
            Log.i("Text before Edit",""+tv.getText());
            tv.setText("MODIFIED");
            Log.i("Text after Edit",""+tv.getText());




        }
        // TODO Auto-generated method stub

    }





}

第一个片段:

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

public class FirstFragment extends Fragment {
    int mNum;


    /**
     * Create a new instance of FirstFragment, providing "num"
     * as an argument.
     */
    static FirstFragment newInstance(int num) {

        FirstFragment f = new FirstFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.myfrag1, container, false);
        return v;
    }




}

第二个片段:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.SupportActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;

public  class SecondFragment extends Fragment {
    int mNum;
    OnButtonClickedXListener mListener;

    /**
     * Create a new instance of CountingFragment, providing "num"
     * as an argument.
     */
    static SecondFragment newInstance(int num) {
        SecondFragment f = new SecondFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

    /**
     * When creating, retrieve this instance's number from its arguments.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNum = getArguments() != null ? getArguments().getInt("num") : 1;
    }

    /**
     * The Fragment's UI is just a simple text view showing its
     * instance number.
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.myfrag2, container, false);
        View button1 = v.findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mListener.OnButtonClickedX(v);
                // TODO Auto-generated method stub

            }
        });



        return v;
    }

    public interface OnButtonClickedXListener{
        public void OnButtonClickedX(View v);
    }

    @Override
    public void onAttach(SupportActivity activity) {
        // TODO Auto-generated method stub
        super.onAttach(activity);
        try {
            mListener = (OnButtonClickedXListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement OnButtonClickedXListener");
        }
    }

}

myfrag1.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" >



    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:text="No String"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

myfrag2.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Button" />

</LinearLayout>

EDIT:

即使将 ft.add() 中的 ContainerViewId 更改为 0,也不会影响最终渲染。所以我猜渲染是由

mTabsAdapter.addTab(tab1, FirstFragment.class);
mTabsAdapter.addTab(tab2, SecondFragment.class);

无论如何,问题仍然是一样的。

Here's actionbar_tabs_pager.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

SOLVED!

压倒一切实例化项目()在 TabsAdapter 中并将 ViewPager 添加为 FragmentTransaction 中的 ContainerViewID 即可!

这是整个 FragmentActivity 的功能!

import java.util.ArrayList;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ActionBar.Tab;
import android.support.v4.app.SupportActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;

/**
 * Demonstrates combining the action bar with a ViewPager to implement a tab UI
 * that switches between tabs and also allows the user to perform horizontal
 * flicks to move between the tabs.
 */
public class ActionBarTabsPager extends FragmentActivity implements SecondFragment.OnButtonClickedXListener{
    ViewPager  mViewPager;
    TabsAdapter mTabsAdapter;
    FragmentManager fm;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.i("ONCREATE START","ONCREATE START");


        setContentView(R.layout.actionbar_tabs_pager);


        if (savedInstanceState == null) {


            Fragment newFragment = new FirstFragment();
            Fragment newFragment2 = new SecondFragment();

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.add(R.id.pager, newFragment, "FirstFragment");
            ft.add(R.id.pager, newFragment2, "SecondFragment");
            ft.commit();


       }

        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        ActionBar.Tab tab1 = getSupportActionBar().newTab().setText("Fragment 1");
        ActionBar.Tab tab2 = getSupportActionBar().newTab().setText("Fragment 2");
        //ActionBar.Tab tab3 = getSupportActionBar().newTab().setText("Fragment 1");
        //ActionBar.Tab tab4 = getSupportActionBar().newTab().setText("Fragment 2");

        mViewPager = (ViewPager)findViewById(R.id.pager);
        mTabsAdapter = new TabsAdapter(this, getSupportActionBar(), mViewPager);

            mTabsAdapter.addTab(tab1, FirstFragment.class);
            mTabsAdapter.addTab(tab2, SecondFragment.class);//LoaderCursorSupport.CursorLoaderListFragment.class);
            //mTabsAdapter.addTab(tab3, FirstFragment.class);//LoaderCustomSupport.AppListFragment.class);
            //mTabsAdapter.addTab(tab4, SecondFragment.class);//LoaderThrottleSupport.ThrottledLoaderListFragment.class);



        if (savedInstanceState != null) {
            getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt("index"));
        }

        Log.i("ONCREATE END","ONCREATE END");

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        Log.i("onSaveInstanceState START","onSaveInstanceState START");
        super.onSaveInstanceState(outState);
        outState.putInt("index", getSupportActionBar().getSelectedNavigationIndex());
        Log.i("onSaveInstanceState END","onSaveInstanceState END");

    }

    /**
     * This is a helper class that implements the management of tabs and all
     * details of connecting a ViewPager with associated TabHost.  It relies on a
     * trick.  Normally a tab host has a simple API for supplying a View or
     * Intent that each tab will show.  This is not sufficient for switching
     * between pages.  So instead we make the content part of the tab host
     * 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
     * view to show as the tab content.  It listens to changes in tabs, and takes
     * care of switch to the correct paged in the ViewPager whenever the selected
     * tab changes.
     */
    public class TabsAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
        private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<String> mTabs = new ArrayList<String>();
        private FragmentTransaction mCurTransaction = null;


        public TabsAdapter(FragmentActivity activity, ActionBar actionBar, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mActionBar = actionBar;
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);


        }

        public void addTab(ActionBar.Tab tab, Class<?> clss) {
            Log.i("addTab","addTab");

            mTabs.add(clss.getName());
            mActionBar.addTab(tab.setTabListener(this));
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return mTabs.size();
        }

        @Override
        public Object instantiateItem(View container, int position) {
            if (mCurTransaction == null) {
                mCurTransaction = getSupportFragmentManager().beginTransaction();
            }
            // TODO Auto-generated method stub
            Fragment fragment = getItem(position);

            if (fragment!=null){
                Log.i("Fragment Found!","Fragment Found! "+fragment.getTag());
                mCurTransaction.attach(fragment);
                }


            return fragment;//super.instantiateItem(container, position);
        }

        @Override
        public Fragment getItem(int position) {
            Log.i("getItem","getItem");

            if (position==0)
                {Log.i("position=0","position=0");
                return getSupportFragmentManager().findFragmentByTag("FirstFragment");}

            else if (position==1)
            {Log.i("position=1","position=1");
                return getSupportFragmentManager().findFragmentByTag("SecondFragment");}

            else return null;//Fragment.instantiate(mContext, mTabs.get(position), null);

        }


        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }

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

        }

        @Override
        public void onTabReselected(Tab tab, FragmentTransaction ft) {
        }

        @Override
        public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        }


    }

    @Override
    public void OnButtonClickedX(View v) {

        if (v==findViewById(R.id.button1)){
            Log.i("TRIGGERED","TRIGGERED");

            FirstFragment ff = (FirstFragment) getSupportFragmentManager().findFragmentByTag("FirstFragment");

            View root = ff.getView();
            TextView tv = (TextView) root.findViewById(R.id.textView1);
            Log.i("Text before Edit",""+tv.getText());
                  tv.setText("MODIFIED");
                  Log.i("Text after Edit",""+tv.getText());




        }
        // TODO Auto-generated method stub

    }





}

感谢vb史蒂文!

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

从另一个 Fragment 更新 ViewPager 中的 TextView 的相关文章

随机推荐

  • ORA-01704: 字符串文字太长 '在 Oracle XMLTYPE 列类型中插入 XML 文档时出错'

    当我尝试将 SQL 表中的数据插入 Oracle 表时 出现此错误 ORA 01704 字符串文字太长 在我的 Oracle 表中 有一列具有 XMLTYPE 列类型 当我创建表时 我指定了 XML 列 如下所示 CREATE TABLE
  • phpmyadmin、neginx error.log - 检查组 www-data 是否具有读取权限和 open_basedir

    我在 phpmyadmin 网站上有此消息 phpMyAdmin 配置存储未完全配置 一些扩展功能已被停用 要了解原因 请点击此处 在 单击此处 页面上 我有以下内容 页面打印屏幕 https www dropbox com s vhh4v
  • 在 Swift 中从 AVCaptureSession 捕获静态图像

    我有一个AVCaptureSession在 UIView 中显示实时视频 我想将视频流的一帧保存为 UIImage 我一直在剖析我在互联网上不断看到的代码 但我在第一行遇到了问题 if let stillOutput self stillI
  • 在打字稿文件上启用 Eslint

    在 webstorm eslint 设置中 有一个 额外 eslint 选项 字段 在此 我补充道 ext ts 来自埃斯林特文档 http eslint org docs user guide command line interface
  • 乘客问题:“没有要加载的文件”--/config/environment

    我一直在研究这个问题 并到处发现类似问题的参考资料 但尚未找到解决方案 我已经安装了 guest 2 2 11 和 nginx 0 7 64 当我启动并点击 Rails URL 时 我收到一个错误页面 通知我加载错误 没有要加载的文件 pa
  • 按下“Ctrl + C”按钮处理 C# 控制台应用程序

    如何处理同时按下的两个按钮 Ctrl C 不是在 WindowsForms 应用程序中 而是在控制台 C 应用程序中 我怀疑你想设置Console TreatCtrlCAsInput http msdn microsoft com en u
  • UIBarButton 没有改变

    IBOutlet weak var playStopButton UIBarButtonItem var playStopArray UIBarButtonSystemItem Pause UIBarButtonSystemItem Pla
  • pandas udf showString 简单示例错误

    我开始在使用此 身份 pandas udf 在 EMR 集群上运行的 Pyspark Jupyter 笔记本上使用 pandas udf 并且收到以下错误 pandas udf df schema PandasUDFType GROUPED
  • 批量将文件从子文件夹移动到父文件夹

    这是我的场景 这是我的文件夹结构 C DOCS Project1 docname1 image jpg docname2 image jpg docname3 image jpg C DOCS Project2 docname1 image
  • 什么样的面试问题适合 C++ 手机屏幕?

    很想了解人们的想法 我经常进行采访 在我的职业生涯中已经有足够多的时间来反思这些采访 并且我注意到了各种各样的问题 我专门做了这个 C 但值得注意的是 有人通过电话问我算法复杂性问题 我什至不是指哈希查找与二叉树的复杂性 我的意思更像是分析
  • 在 Oracle SQL / PL-SQL 中将德语特殊字符转换为英语等效字符

    我想将表的一列中的所有德语字符替换为相应的英语字符 当我尝试使用 Replace 函数时 它没有返回丰硕的结果 我想将所有德语特殊字符替换为 Ae Oe Ue oe ae ue ss 请让我知道如何执行 我需要更改任何数据库设置吗 请在下面
  • Python 3.4 解码字节

    我正在尝试用 python 编写一个文件 并且在编写文件之前找不到解码字节对象的方法 基本上 我正在尝试解码这个字节字符串 Les xc3 x83 xc2 xa9vad xc3 x83 xc2 xa9s 这是我试图恢复的原始文本 Les v
  • 使用 .net core 为 NLog 注入服务的自定义目标

    我正在使用 NLogNLog Extensions Logging用于 aps net 核心支持 我需要创建一个自定义目标并将服务注入到目标的构造函数中 以下代码永远不会被执行 public MyTarget IService servic
  • 在前台服务中运行网络代码后仍然收到“网络使用过多(后台)”警告

    通过参考处理和解决 网络使用过多 后台 的正确方法 https stackoverflow com questions 54489501 proper way to tackle and resolve excessive network
  • 最短路径图算法助力Boost

    我有一个矩形网格形状的 DAG 其中水平边缘始终指向右侧 垂直边缘始终指向下方 边缘具有与之相关的正成本 由于矩形格式 节点使用从零开始的行 列来引用 这是一个示例图 现在 我想进行搜索 起始顶点将始终位于左列 索引为 0 的列 和图的上半
  • 在链接上切换活动课程

    给定一个在两个类之间切换的脚本 我还向当前选定的链接添加一个活动状态 以设置下划线来显示活动状态 但是 当连续单击链接时 它会不断添加活动类 而不是打开和关闭该类 如何在单击链接时显示活动状态 并在单击另一个链接时关闭并应用于另一个链接 J
  • Excel 文件的 Oledb 连接字符串

    这是我在加载 excel 2003 文件时使用的 oledb 连接字符串 但我收到错误消息 无法找到可安装的 ISAM 请帮助我解决这个问题 我在这里做错了什么 Provider Microsoft Jet OLEDB 4 0 Data S
  • 订阅 DTE 事件似乎不起作用 - 事件不会被调用

    我在包内进行了扩展 并调用以下代码 当用户按下工具栏中的按钮时发生 DocumentEvents documentEvents DTE2 GetService typeof DTE dte Events DebuggerEvents OnE
  • FOS Js 路由包无法识别路由

    我正在尝试使用FOSJsRoutingBundle从 symfony 路由生成 url 我遵循doc https github com FriendsOfSymfony FOSJsRoutingBundle blob master Reso
  • 从另一个 Fragment 更新 ViewPager 中的 TextView

    我正在尝试单击另一个片段上的按钮来更新片段中的 TextView 实际上 我对 Activity 实现了回调函数 并且它确实有效 因为 Logcat 报告 TextView 中的文本已更改 问题是第一个片段中显示的 Textview 没有更