将参数从onCreate传递给onClick

时间:2019-02-18 11:32:09

标签: android kotlin

这是我的kotlin / android活动:

import kotlinx.android.synthetic.main.activity_player_details.*

class PlayerDetails : AppCompatActivity(), View.OnClickListener {

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

        val intent = getIntent()
        val numOfPlayers = intent.getIntExtra("number_of_players", 1)    
        next_details.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        for (player in 1..numOfPlayers) {
            // body in here

        }
    }

}

我想将numOfPlayers的值传递给我的onClick方法,以便可以使用它-如何实现呢?

4 个答案:

答案 0 :(得分:2)

要么将numOfPlayer用作全局变量,要么创建单击btn时要调用的单独函数,然后将numOfPlayer用作参数

1。将numOfPlayer设置为全局变量

class PlayerDetails : AppCompatActivity(), View.OnClickListener {
    var numOfPlayers = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player_details)

        val intent = getIntent()
        numOfPlayers = intent.getIntExtra("number_of_players", 1)
        next_details.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        for (player in 1..numOfPlayers) {
            // body in here
        }
    }
}

2。创建单独的函数以在单击btn时调用,并将numOfPlayer作为参数传递

class PlayerDetails : AppCompatActivity(), View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player_details)
        val intent = getIntent()
        val numOfPlayers = intent.getIntExtra("number_of_players", 1)
        bottomNav.setOnClickListener {
            onNextClick(numOfPlayers)
        }
    }

    private fun onNextClick(numOfPlayers: Int) {
        for (player in 1..numOfPlayers) {
            // body in here
        }
    }
}

答案 1 :(得分:0)

使用如下所示的全局范围定义变量

var numOfPlayers = 0

确保在onCreate()方法上方定义它。

答案 2 :(得分:0)

onCreate在创建活动时被调用,而onClick在单击next_details按钮时被调用,这肯定在onCreate之后发生。

因此,将numOfPlayers设为一个类成员,并在onCreate中为其分配值,然后将lateinit关键字添加到numOfPlayers中,因此您无需设置它可以为空。

代码应如下所示:

import kotlinx.android.synthetic.main.activity_player_details.*

class PlayerDetails : AppCompatActivity(), View.OnClickListener {

    lateinit var numOfPlayers: Integer
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_player_details)

        val intent = getIntent()
        numOfPlayers = intent.getIntExtra("number_of_players", 1)    
        next_details.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        for (player in 1..numOfPlayers) {
            // body in here

        }
    }

}

答案 3 :(得分:0)

使numOfPlayers为全局 my_dict_1

var numOfPlayers =0

onCreate()

在onClick()

val intent = getIntent()
numOfPlayers = intent.getIntExtra("number_of_players", 1)