单击列表项时如何从一个片段切换到另一个片段?

时间:2019-06-27 05:44:26

标签: android android-fragments kotlin

我在“所有用户”片段中都有一个列表。单击列表上的名称时,应切换到“用户详细信息”片段。我似乎找不到办法以某种方式销毁此碎片并提出新的碎片,或者只是在旧的碎片上显示新的碎片。

使用的语言是Kotlin。我是新来的。我用Fragment Manager尝试了一些方法,但似乎找不到正确的语法。

主要活动.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Default view when app starts
        title = resources.getString(R.string.allusers)
        loadFragment(AllUsersFragment())

        //Bottom Navigation Bar
        navigationView.setOnNavigationItemSelectedListener {
            when (it.itemId) {
                R.id.navigation_allusers -> {
                    title = resources.getString(R.string.allusers)
                    loadFragment(AllUsersFragment())
                    return@setOnNavigationItemSelectedListener true
                }

                R.id.navigation_transfer -> {
                    title = resources.getString(R.string.transfer)
                    loadFragment(TransferFragment())
                    return@setOnNavigationItemSelectedListener true
                }

                R.id.navigation_logs -> {
                    title = resources.getString(R.string.logs)
                    loadFragment(LogsFragment())
                    return@setOnNavigationItemSelectedListener true
                }

            }
            false

        }
    }

    //function to load fragment when bottom navigation is clicked

    fun loadFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.container, fragment)
        transaction.addToBackStack(null)
        transaction.commit()
    }

}

AllUsersFragment.kt

class AllUsersFragment : Fragment(){

    private lateinit var listView:ListView

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView = inflater.inflate(R.layout.fragment_allusers, container, false)
        val details = UserDetailsFragment()
        val bundle = Bundle()                //To transfer information

        listView = rootView.findViewById(R.id.usersList)

        val userNames = arrayOf(
            "Andrew Jackson",
            "Barry Alan",
            "Caitlyn Snow",
            "Drake Ramoray"
        )

        val adapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, userNames)
        listView.adapter = adapter

        //List view item clicked listener
        listView.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->

            val userName = userNames[i]
            bundle.putString("str", userName)
            bundle.putInt("int", i)
            details.arguments = bundle
        }

        return rootView
    }
}

UserDetails.kt

class UserDetailsFragment : Fragment(){
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val rootView =  inflater.inflate(R.layout.fragment_user_details,container,false)

        val nameField = rootView.findViewById<TextView>(R.id.nameField)
        val imageField = rootView.findViewById<ImageView>(R.id.imageField)

        //Importing images
        val andrewjackson = BitmapFactory.decodeResource(context!!.resources,R.drawable.andrewjackson)
        val barryalan = BitmapFactory.decodeResource(context!!.resources,R.drawable.barryalan)
        val caitlynsnow = BitmapFactory.decodeResource(context!!.resources,R.drawable.caitlynsnow)
        val drakeramoray = BitmapFactory.decodeResource(context!!.resources,R.drawable.drakeramoray)

        val userImages = ArrayList<Bitmap>()

        userImages.add(andrewjackson)
        userImages.add(barryalan)
        userImages.add(caitlynsnow)
        userImages.add(drakeramoray)

        val name = arguments!!.getString("str")     //Displays name clicked on Details Page
        nameField.setText(name)

        val i =arguments!!.getInt("int")               //Displays image of user from array
        imageField.setImageBitmap(userImages[i])

        return rootView
    }
}

我认为可以在loadFragment中使用MainActivity.kt函数,但是我想不出一种在片段中使用该函数的方法。

预期输出:

单击列表上的名称后,它应更改为同一容器中的另一个片段,以显示用户详细信息。

3 个答案:

答案 0 :(得分:2)

您可以在片段中使用此代码替换容器中的片段

val someFragment = YourUserDetailsFragment()
val transaction = fragmentManager!!.beginTransaction()
transaction.replace(R.id.container, someFragment)
transaction.addToBackStack(null)
transaction.commit()

答案 1 :(得分:1)

是的,有两种方法可以使用Interface和public方法。由于片段与活动绑定,这意味着活动是父项。

因此,您可以使用

来访问仅用于使公共不活动和访问的方法。
(activity as MainActivity).loadFragment(//Your fragment intance)

Here是在活动和片段之间进行通信的示例。

答案 2 :(得分:1)

您已经完成了所有设置,在点击监听器中,您只需致电activity?.loadFragment(UserDetailsFragment())

 listView.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
        val userName = userNames[i]
        bundle.putString("str", userName)
        bundle.putInt("int", i)
        details.arguments = bundle
        (activity as MainActivity)?.loadFragment(details)
    }