使用kotlin 進行 安卓app 的 活動跳轉 與 片段跳轉

activity 跳轉

活動跳轉 性能低於 片段跳轉,但是使用也很多

具體代碼

//重載 活動創建函數
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_first)
        
        //獲得意圖 意圖最好不要定義在回調函數中中
        val intent1= Intent(this,ScrollingActivity::class.java).apply{}

        findViewById<Button>(R.id.button_first).apply {
            setOnClickListener {
            	// 執行 意圖 跳轉另一個 activity
                startActivity( intent1 )
            }
        }
    }

fragment 跳轉

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

//根據 R.id.action_FirstFragment_to_SecondFragment 進行跳轉
// 這個東西可以理解爲流向,可以在 res navigation 中進行定義
        view.findViewById<Button>(R.id.button_first).setOnClickListener {
            findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
        }
    }

activity 傳遞參數

發送方活動 發送參數

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_first)
        val name1=R.string.lmk123

//放置參數到 intent 中
        val intent1= Intent(this,ScrollingActivity::class.java).apply{
                putExtra("var1","參數1")}


        findViewById<Button>(R.id.button_first).apply {
            setOnClickListener {
                startActivity( intent1)
            }
        }
    }

接收方活動 接收參數

    override fun onCreate(savedInstanceState: Bundle?) {
//。。。。。
//。。。。。
  //接收參數
        val name1 = intent.getStringExtra("var1")
        findViewById<TextView>(R.id.t5).apply { text=name1 }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章