4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Kotlinで一度しか行わない処理を実現する

4
Last updated at Posted at 2018-08-22

いわゆる、onceですね
以下のコードはAndroid studioのBase Activityのテンプレートコードを改修しています。

class BasicActivity : AppCompatActivity() {

    val onceExecute: Runnable? by lazy {
        //ここに、一度しかやらない処理を書く
        Log.d("TAG","execute!")
        null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_basic)
        setSupportActionBar(toolbar)

        fab.setOnClickListener { view ->
            onceExecute?.run() //一度しか行わない処理
        }
    }

}

lazyを利用して、onceExecute内に処理を書いて、最後にnullを返します。
onceExecuteの返却はRunnableである必要はないのですが、.run()で繋げたほうが可読性としては良さそうなのでそうしてます。

4
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?