gpt4 book ai didi

android - 将数据从 Activity 发送到 Tab Fragment

转载 作者:太空宇宙 更新时间:2023-11-03 12:47:51 28 4
gpt4 key购买 nike

我的代码有一个小问题,我在这个网站上搜索但仍然没有找到最佳答案我会将数据发送到我的标签 fragment ,这是我的代码

我的 Activity 类

public class MainActivity extends AppCompatActivity 

private ViewPager pager;
private Toolbar toolbar;
private TabLayout tabs;

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


pager=(ViewPager) findViewById(R.id.pager);
tabs=(TabLayout) findViewById(R.id.tabs);

pager.setAdapter(new TabFragmentPagerAdapter(getSupportFragmentManager()));
tabs.setupWithViewPager(pager);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);

Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
// set Fragmentclass Arguments
tab1Fragment fragobj = new tab1Fragment();
fragobj.setArguments(bundle);

}
}

这是我的 tab1 类

public class tab1Fragment extends Fragment 

public tab1Fragment() {
// Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment

View view= inflater.inflate(R.layout.fragment_tab1, container, false);
TextView tes=(TextView) view.findViewById(R.id.testtab1);
String strtext = getArguments().getString("edttext");

tes.setText("tes :"+ strtext);
return view;
}
}

还有这个我的页面 fragment 适配器

public class TabFragmentPagerAdapter extends FragmentPagerAdapter 

String[] title = new String[]{
"Tab 1", "Tab 2", "Tab 3"
};

public TabFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position){
Fragment fragment=null;
switch (position){
case 0:
fragment=new tab1Fragment();
break;
case 1:
fragment=new tab2Fragment();
break;
case 2:
fragment=new tab3Fragment();
break;
default:
fragment=null;
break;
}
return fragment;
}
@Override
public CharSequence getPageTitle(int position){
return title[position];
}
@Override
public int getCount(){
return title.length;
}
}

当我运行错误时

java.lang.NullPointerException

请帮忙

最佳答案

在您的 AppCompatActivity 中,您已发送

tab1Fragment fragobj = new tab1Fragment();
fragobj.setArguments(bundle);

但是在你的TabFragmentPagerAdapter

fragment=new tab1Fragment();
break;

它有空参数

内部开关

switch (position){
case 0:
fragment=new tab1Fragment();
Bundle bundle = new Bundle();
bundle.putString("edttext", "data From Activity");
fragment.setArguments(bundle);
break;

关于android - 将数据从 Activity 发送到 Tab Fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887498/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com