简体   繁体   English

如何使用 TabLayout 将数据从 Activity 传递到 Fragment

[英]How to pass data from Activity to Fragment with TabLayout

I have been trying to pass data from Main Activity to fragments using bundle.我一直在尝试使用 bundle 将数据从主活动传递到片段。 I have used TabLayout and ViewPager to add fragments on my activity in Tab format.我使用 TabLayout 和 ViewPager 以 Tab 格式在我的活动中添加片段。 I don't get any error but I get a null object in return and it displays "ERROR" on my 1st fragment as I have added an If condition for null object.我没有收到任何错误,但我得到一个空对象作为回报,它在我的第一个片段上显示“错误”,因为我为空对象添加了 If 条件。 This is my code这是我的代码

Main Activity Code主要活动代码

package com.example.activitytofragmenttest;

import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    TextView textView;
    private ViewPager viewPager;
    private ViewPagerAdapter viewPagerAdapter;
    private TabLayout tabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Text View
        textView = findViewById(R.id.mainTextView);

        //TabLayout and ViewPager
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        tabViewPager();

        Bundle bundle = new Bundle();
        String message = textView.getText().toString();
        bundle.putString("key",message);
        Fragment_1 fragment_1 = new Fragment_1();
        fragment_1.setArguments(bundle);

        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void tabViewPager() {
        viewPagerAdapter.AddFragment(new Fragment_1(),"Frag1");
        viewPagerAdapter.AddFragment(new Fragment_2(),"Frag2");
        viewPagerAdapter.AddFragment(new Fragment_3(),"Frag3");
    }
}

ViewPager Code ViewPager 代码

package com.example.activitytofragmenttest;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import java.util.ArrayList;
import java.util.List;

public class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> listFragment = new ArrayList<>();
    private final List<String> listTitle = new ArrayList<>();


    public ViewPagerAdapter(@NonNull FragmentManager fm) {
        super(fm);
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        return listFragment.get(position);
    }

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

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        return listTitle.get(position);
    }


    public void AddFragment (Fragment fragment, String title){
        listFragment.add(fragment);
        listTitle.add(title);
    }
}

Fragment 1 Code片段 1 代码

package com.example.activitytofragmenttest;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment_1 extends Fragment{

    TextView fragment_1TextView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_1,container,false);

        fragment_1TextView = v.findViewById(R.id.fragment1TextView);
        Bundle message = getArguments();
        if (message != null){
            fragment_1TextView.setText(message.getString("key"));
        }else {
            fragment_1TextView.setText("Error");
        }
        return v;
    }
}

Fragment 2 Code片段 2 代码

package com.example.activitytofragmenttest;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment_2 extends Fragment {
    TextView fragment_2TextView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_2, container, false);

        fragment_2TextView = v.findViewById(R.id.fragment2TextView);
//        Bundle bundle = getArguments();
//        if (bundle != null) {
//            fragment_2TextView.setText(bundle.getString("key"));
//        }
        return v;
    }
}

Fragment 3 Code片段 3 代码

package com.example.activitytofragmenttest;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class Fragment_3 extends Fragment {
    TextView fragment_3TextView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_3, container, false);

        fragment_3TextView = v.findViewById(R.id.fragment3TextView);
//        Bundle bundle = getArguments();
//        if (bundle != null) {
//            fragment_2TextView.setText(bundle.getString("key"));
//        }
        return v;
    }
}

Can anyone suggest why I get a null object from the Main Activity to fragment, and how can I transfer multiple data from the Main Activity to other fragments as well that is 2nd and 3rd fragment.任何人都可以建议为什么我从主活动获取空对象到片段,以及如何将多个数据从主活动传输到其他片段以及第二和第三片段。

When starting the Fragment you can pass parameters through a bundle启动 Fragment 时,您可以通过捆绑包传递参数

/*ACTIVITY CODE*/
Bundle args = new Bundle();
args.putStringArrayList("argument_name", myListInString);
MyFragment fragment = new MyFragment();
fragment.setArguments(args);
fragment.show(fragmentTransaction, "fragment_tag")

And use them in your new snippet as follows并在您的新代码段中使用它们,如下所示

/* FRAGMENT CODE */
ArrayList<String> myList = getArguments.getStringArrayList("argument_name");
// ... FILL TABLE

This is a code ordering and scope issue.这是代码排序和范围问题。

You create a new Fragment_1 in您在中创建一个新的Fragment_1

viewPagerAdapter.AddFragment(new Fragment_1(),"Frag1");

and store it in the ViewPagerAdapter , this has no Bundle attached.并将其存储在ViewPagerAdapter ,它没有附加 Bundle。

You then later create a new instance of Fragment_1 in the local scope of of oncreate and attach the Bundle to it and then throw this instance away.然后,您稍后在oncreate的本地范围内创建Fragment_1的新实例并将 Bundle 附加到它,然后将这个实例扔掉。

A better ordering of the code.更好的代码排序。

        //....
        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        Bundle bundle = new Bundle();
        String message = textView.getText().toString();
        bundle.putString("key",message);
        Fragment_1 fragment_1 = new Fragment_1();
        fragment_1.setArguments(bundle);

        // Add the existing instance of the Fragment_1 to the viewpager instead of creating another new instance.
        viewPagerAdapter.AddFragment(fragment_1,"Frag1");
        viewPagerAdapter.AddFragment(new Fragment_2(),"Frag2");
        viewPagerAdapter.AddFragment(new Fragment_3(),"Frag3");

        viewPager.setAdapter(viewPagerAdapter);
        //....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM