我知道有一些问题可以解决这个问题,但是地雷有点不同,因为它没有使用fragment
转换(我不知道它是如何工作的所以我没有使用它)。
我的MainActivity
做了什么,它在fragments
上添加tabBar
并创建了将消息数据从一个fragment
传递到另一个fragment
的函数。
public class MainActivity extends AppCompatActivity implements InputTab.SendMessage, FollowingTab.SendMessage, FollowerTab.SendMessage, ProfileTab.SendMessage, UserSearchResultTab.SendMessage {
private SectionsPageAdapter pageAdapter;
ViewPager viewPager;
public static String currentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, new ProfileTab());
fragmentTransaction.commit();
pageAdapter = new SectionsPageAdapter(getSupportFragmentManager());
// Sets up the ViewPager with the sections adapter
viewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(viewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager((viewPager));
}
// Adds fragments to SectionsPageAdapter and gives names for the corresponding tab
private void setupViewPager(ViewPager viewPager) {
SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
adapter.addFragment(new InputTab(), "Search");
adapter.addFragment(new ProfileTab(), "Profile");
adapter.addFragment(new GithubTab(), "Github Repos");
adapter.addFragment(new FollowerTab(), "Followers");
adapter.addFragment(new FollowingTab(), "Followings");
adapter.addFragment(new UserSearchResultTab(), "test");
viewPager.setAdapter(adapter);
}
@Override
public void sendDataToProfile(String message) {
String tag = "android:switcher:" + R.id.container + ":" + 1;
ProfileTab profile = (ProfileTab) getSupportFragmentManager().findFragmentByTag(tag);
profile.displayReceivedData(message);
}
@Override
public void sendDataToFollowers(String message) {
String tag = "android:switcher:" + R.id.container + ":" + 3;
FollowerTab follower = (FollowerTab) getSupportFragmentManager().findFragmentByTag(tag);
follower.displayReceivedData(message);
}
数据成功传入profileTab
,但是当我调试它时,它会为null
提供其他标签,例如
FollowerTab follower = (FollowerTab) getSupportFragmentManager().findFragmentByTag(tag);
这一个。因此,每当我尝试将数据发送到FollowerTab
时,它就会崩溃。
我缺少什么,如何让它成为非空fragment
?
答案 0 :(得分:0)
在片段事务处理时,您需要为片段添加标记。您尚未为片段设置任何标记。这就是你得到null的原因。 你需要在你的片段中添加标签。
FragmentA fragment=new FragmentA();
getSupportFragmentManager()
.beginTransaction().replace(R.id.container,fragment,"tag").commit();
此处标签在您使用findFragmentByTag(tag);
时返回标签