简体   繁体   English

将数据从“活动”传递到“选项卡式布局片段”?

[英]Passing a data from Activity to Tabbed Layout Fragment?

I have two Activities. 我有两个活动。 One is normal Activity which contains listview and second one is Tabbed Layout which it have two tabs. 第一个是包含列表视图的普通活动,第二个是带有两个选项卡的选项卡式布局。 One is "Description" tab and another one is "Sample Code" tab. 一个是“描述”选项卡,另一个是“样本代码”选项卡。

I have created two seperate fragments for each namely "OneFragment" and "TwoFragment". 我为每个创建了两个单独的片段,即“ OneFragment”和“ TwoFragment”。 All i need is when user click an Item from my normal Activity, this item will be stored in string and that string should be passed to Tabbed layout and it should be showed in OneFragment ie., "Description" tab 我需要做的就是,当用户单击我正常活动中的某个项目时,该项目将存储在字符串中,并且该字符串应传递到选项卡式布局,并应显示在OneFragment中,即“说明”选项卡

(Ex). (例)。 My List Contains {"Android","Studio"} if user clicks Android,this text should pass to description tab and showed the text using TextView. 我的列表包含{“ Android”,“ Studio”}如果用户单击Android,则此文本应传递到说明标签,并使用TextView显示该文本。 please help me. 请帮我。 Here i include my respective codes.. 在这里,我包括我各自的代码。

NormalActivity - >ListActi.java NormalActivity-> ListActi.java

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        lv = (ListView) findViewById(R.id.listView);
        final List<String> ListElementsArrayList = new ArrayList<String>(Arrays.asList(listElements));
        final ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (getApplicationContext(), android.R.layout.simple_list_item_1, ListElementsArrayList);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Toast.makeText(getApplicationContext(), listElements[position],Toast.LENGTH_LONG).show();
                s = listElements[position];
                if(position == 1){
                    s = listElements[position];
                    Bundle bundle = new Bundle();
                    bundle.putString("ClickedItem", listElements[position]);
                    OneFragment fragobj = new OneFragment();
                    TwoFragment fag = new TwoFragment();
                    fragobj.setArguments(bundle);
                    fag.setArguments(bundle);
                    Intent i = new Intent(getApplicationContext(),BothLay.class);
                    startActivity(i);
                }
           }
        });
    }
}

TabActivity - > BothLay TabActivity-> BothLay

public class BothLay extends AppCompatActivity  {
    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_both_lay);
        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }
    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "Description");
        adapter.addFragment(new TwoFragment(), "Sample Code");
        viewPager.setAdapter(adapter);
    }
    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();
        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }
        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }
        @Override
        public int getCount(){
            return mFragmentList.size();
        }
        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }
        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

Decription tab - >OneFragment (All i need is pass a data from Normal Activity to this Fragment) 解密选项卡-> OneFragment (我所需要的只是将数据从“正常活动”传递到此Fragment)

public class OneFragment extends Fragment{
    String strtext = "Ajay";
    public OneFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootview = inflater.inflate(R.layout.fragment_one, container, false);
        TextView textView = (TextView) rootview.findViewById(R.id.t1);
        //strtext = getIntent().getStringExtra("ClickedItem"); //this doesn't work  
        textView.setText(strtext);
        return rootview;
    }
}

Sample Code tab ->Twofragment 样本代码选项卡-> Twofragment

public class TwoFragment extends Fragment{
    public TwoFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_two, container, false);
    }

}

Here: 这里:

fragobj.setArguments(bundle);
fag.setArguments(bundle);

Not work on click of Button because currently starting BothLay Activity instead of adding Fragment to FragmentManager . 单击按钮不起作用,因为当前正在启动BothLay Activity,而不是将Fragment添加到FragmentManager

To get it work: 要使其正常工作:

1. Pass bundle using Intent to BothLay Acivity on Click of Button: 1.单击按钮时,将使用Intent的包传递给BothLay Acivity:

  Intent i = new Intent(getApplicationContext(),BothLay.class);
  i.putExtras(bundle);
  startActivity(i);

2. Get Bundle from Intent in onCreate of BothLay Activity then pass it to Fragment's when calling adapter.addFragment method: 2.BothLay Activity的onCreate的Intent中获取Bundle,然后在调用adapter.addFragment方法时将其传递给Fragment的:

  Bundle bundle = getIntent().getExtras();
  tabLayout.setupWithViewPager(viewPager,bundle);

Pass bundle to Fragment objects: 将捆绑包传递给Fragment对象:

   private void setupViewPager(ViewPager viewPager,Bundle bundle) {
        ...
        Fragment fragmentOne=new OneFragment();
        fragmentOne.setArguments(bundle);
        adapter.addFragment(fragmentOne, "Description");
        // do same for second Framgment
   }

EDIT: 编辑:

To get data in Fragment call getArguments method in onCreateView of Fragment: 要在Fragment中获取数据,请在Fragment的onCreateView中调用getArguments方法:

Bundle bundle=getArguments();
if(bundle!=null){
  if(bundle.containsKey("ClickedItem")){
     String strClickedItem=bundle.getString("ClickedItem");
   }
}

Do all steps which i provide the link. 做我提供链接的所有步骤。

And the 4th step need to be implemented when your fragment is resumed. 恢复片段后,需要执行第四步。

below code will be in your activity, 下面的代码将出现在您的活动中,

SelectedBundle selectedBundle; SelectedBundle selectedBundle;

finally you will get the instance of fragment on selectedBundle. 最后,您将在selectedBundle上获得fragment的实例。

so, you can easily pass the value to the fragment. 因此,您可以轻松地将值传递给片段。 Like, 喜欢,

  fragment.setData(String passedData);

that's all. 就这样。

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

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