Android:导航到另一个片段

我有一个ViewPagerTabLayout设置4片段,就像任何现代的社交应用程序。 我尝试过,尝试过,尝试过,但我无法find我的问题的答案。 在其中一个选项卡中,我想从片段导航到另一个片段,但不是导航,而是将其放在顶部,我仍然可以与前一个片段进行交互。 这不是替代,只是把它放在最上面。

码:

 // Chat fragment : Inside the onCreateView fun this.loadConvos({ chats -> this.chatsArray = chats this.chatsArray.sortBy { it.timestamp} this.chatsArray.reverse() listView.adapter = ChatBaseAdapter(this.chatsArray, context) listView.setOnItemClickListener { parent, view, position, id -> this.chatID = this.chatsArray[position].chatID!! Toast.makeText(context, "Position Clicked: " + position, Toast.LENGTH_SHORT).show() childFragmentManager .beginTransaction() .replace(R.id.chatFragmentLayout, MessagesFragment()) .addToBackStack(null) .commit() } }, { error -> print(error) }) 

这个函数只是简单地加载listView和用户拥有的聊天细节,我可以点击,Toast会给我细胞的位置,但是当它commit()时,它只是在ChatsFragment()顶部ChatsFragment() 。 我也想知道如何将信息传递给下一个片段。 这种方法我没有看到传递数据的方式,不像我知道的常规Bundle/Intent方式。

在viewpager上的XML聊天:

    

XML消息

    

如果你试图切换到的Fragment是你的ViewPager中的一个,你不应该通过FragmentTransaction手动改变它。 您应该在ViewPager上调用setCurrentItem() (请参阅联机文档中的此链接 )。 如果这个调用是通过这些片段之一的话,那么你还需要有一些接口来在父Activity和那个Fragment之间进行通信(参见这里 )。

至于你的第二个问题,如果你打算在你的ViewPager中有一个不断变化的Fragment ,你将不得不再次思考这个问题。 否则,你应该看看这个post中讨论的新实例types模式。

碎片有void setArguments(Bundle)Bundle getArguments()方法,您可以使用相同的方式使用一个活动的意图。

例如,从官方文件 。

 public class CountingFragment extends Fragment { private int mNum; public static CountingFragment newInstance(int num) { CountingFragment f = new CountingFragment(); Bundle args = new Bundle(); args.putInt("num", num); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNum = getArguments() != null ? getArguments().getInt("num") : 1; } } 

或者在Kotlin:

 class CountingFragment : Fragment() { companion object { fun newInstance(number: Int): CountingFragment { return CountingFragment().apply { arguments = Bundle().apply { putInt("number", number) } } } } private var number: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) number = arguments?.getInt("number") ?: 0 } }