Java 在使用具有不同片段/布局的视图寻呼机时如何传递片段参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19995074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:09:25  来源:igfitidea点击:

How pass fragment arguments while using a view pager with different fragments/layouts?

javaandroidandroid-fragmentsandroid-viewpagerfragmentpageradapter

提问by Sakiboy

Objective: To use fragment arguments to pass along the string value from a TextViewto a new fragments TextView, BUT while using a ViewPagerwith different layouts/fragmentsin the FragmentPagerAdapter.

目的:为了使用片段参数从一个沿字符串值传递TextView到一个新的片段TextView,但在使用ViewPager具有不同layouts/fragmentsFragmentPagerAdapter

Problem: The new fragment never receives the fragments arguments from the previous fragment.

问题:新片段永远不会从前一个片段接收片段参数。

My Set up: I have my Activityhosting the ViewPagerand FragmentPagerAdapter. I have overridden FragmentPagerAdaptersgetItem(int position)method to create a new fragmentinstance depending on the current position of the ViewPager. Right now I only have two Fragmentsin my adapter, but will be adding more after getting over this obstacle. I am using the newInstance()technique to pass along the Fragment's arguments, but nothing is ever passed.

我的设置:我有我的Activity托管ViewPagerFragmentPagerAdapter。我已经重写FragmentPagerAdaptersgetItem(int position)fragment根据ViewPager. 现在Fragments我的适配器中只有两个,但在克服这个障碍后会添加更多。我正在使用该newInstance()技术传递Fragment的参数,但没有传递任何内容。

Pertinent Code:

相关代码

My FragmentPagerAdapter code:

我的 FragmentPagerAdapter 代码:

//this is a variable that I pass in as the newInstanct() methods parameter,
// I update   this variable from my fragments constantly
public static String fragmentArgumentsValue = "";

mViewPager.setAdapter(new FragmentPagerAdapter(fm) {


            @Override
            public int getCount() {

                return NUMBER_OF_VIEWS;
            }

            @Override
            public Fragment getItem(int position) {
                switch (position) {
                case 0:
                    Log.d(TAG, "---In getPosition(), position 0---");

                    return Frag1
                            .newInstance(fragmentArgumentsValue);

                case 1:
                    Log.d(TAG, "---In getPosition(), position 1---");

                    return frag2
                            .newInstance(fragmentArgumentsValue);

                default:
                    Log.d(TAG, "---In getPosition(), DEFAULT---");

                    return frag1
                            .newInstance(fragmentArgumentsValue);
                }

            }
        });

One of the fragments newInstance() method:

片段 newInstance() 方法之一:

public static Fragment newInstance(String fragmentArgumentsValue) {
    Frag1 f = new Frag1();
    Bundle bun = new Bundle();
    bun.putString(KEY_FRAGMENT_ARGUMENTS_STRING, fragmentArgumentsValue);
    f.setArguments(bun);
    return f;
}

Getting the fragments arguments:

获取片段参数:

String argString = getArguments().getString(
        KEY_FRAGMENT_ARGUMENTS_STRING);
if (argString.length() != 0) {
    Log.d(TAG, "Trying to set the frag args to:" + argString);
    mWorkingTextView.setText("" + argString);
} else {
    Log.d(TAG, "Couldn't set frag args to: " + argString);
}

What I've Tried: I've tried giving the Activitythat hosts the ViewPagerand FragmentPagerAdaptera staticvariable that I constantly update in each one of my fragments, I include the staticvariable in the fragment.newInstance(staticVariableInActivity)method, but this doesn't seem to work. I've also tried using the ViewPagercallback viewPager.setOnPageChangeListener()I had overridden the onPageSelected(int pos)and tried to pass the fragment arguments there, nevertheless it didn't work... so please help me S.O.!!!

我试过的:我试过给Activity主机ViewPagerFragmentPagerAdapter一个static我不断更新的变量,我在方法中fragments包含static变量fragment.newInstance(staticVariableInActivity),但这似乎不起作用。我也尝试使用我已经覆盖的ViewPager回调并尝试在那里传递片段参数,但是它没有用......所以请帮助我!!!viewPager.setOnPageChangeListener()onPageSelected(int pos)

My thoughts: I do not have the different fragmentsand layoutsin an ArrayListor any list for that matter, I just instantiate the Fragmentsvia the newInstance()method depending on the positions of the FragementPagerAdapter, could this be a problem? Should I create a singletonlist of the layouts/fragments? So I can change the values of the FragmentsTextViewsvia the singletonlist? (excuse me if that's a dumb or not possible thing to do).

我的想法:我没有不同的fragmentslayouts在一个ArrayList或任何列表中,我只是根据 的位置实例化FragmentsvianewInstance()方法,这FragementPagerAdapter可能是一个问题吗?我应该创建一个singleton列表layouts/fragments吗?所以我可以FragmentsTextViews通过singleton列表更改的值?(如果这是愚蠢的或不可能的事情,请原谅我)。

Note: I am am saving away the TextViews values via public void onSaveInstanceState(Bundle outState)to handle screen rotations. Could this be a problem?

注意:我正在通过public void onSaveInstanceState(Bundle outState)处理屏幕旋转来保存 TextViews 值。这可能是个问题吗?

采纳答案by Sakiboy

Alright so I this link will help in the communication between fragments: Communication with other Fragments.

好的,所以我这个链接将有助于片段之间的通信:与其他片段通信

You need to define a interface that the Activity will implement and the fragments will use to send data onward to the activity, and the activity will then find the fragment by tag doing something like this:

您需要定义一个接口,Activity 将实现该接口,片段将使用该接口将数据向前发送到 Activity,然后 Activity 将通过标记查找片段,执行如下操作:

frag = (Fragment2) getSupportFragmentManager()
                    .findFragmentByTag(
                            "android:switcher:" + R.id.viewPager + ":2");

and then update the fragment by calling a public method implemented within the fragment.

然后通过调用在片段中实现的公共方法来更新片段。

The link provided will help greatly, it is from the Android Development website.

提供的链接将有很大帮助,它来自 Android 开发网站。

回答by Douglas Mesquita

Adds the bundle inside your Adapter.

在您的适配器中添加包。

example in the constructor of the adapter :

适配器构造函数中的示例:

      public ViewPagerAdapter(Context context, FragmentManager fm) {
        super(fm);
        fragments.add(TileFragments.newInstance());
        Bundle bundleFeatures = new Bundle();
        bundleFeatures.putString(ContentName.FEATURES.toString(),ContentName.FEATURES.toString());

        fragments.get(0).setArguments(bundleFeatures);

    }