Android kotlin fragment中使用布局控件

注意控件不能从 onCreateView中获取,而是要从 onViewCreated中获取和调用,具体代码如下:

package cn.showmac.tool.fragment

import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import cn.showmac.tool.R
import cn.showmac.tool.cos.Device
import cn.showmac.tool.cos.DeviceCallback
import cn.showmac.tool.cos.SharedKeyResponse
import cn.showmac.tool.cos.StateResponse
import kotlinx.android.synthetic.main.fragment_init.*
import org.greenrobot.eventbus.EventBus

/**
 * 描述:初始化的页面
 * 创建人:菜籽
 * 创建时间:2017/12/1 下午3:18
 * 备注:
 */

class InitFragment : Fragment(), View.OnClickListener {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_init, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        get_cos_version.setOnClickListener(this)
        create_key.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.get_cos_version
            ->
                Device.getCosVersion(object : DeviceCallback {
                    override fun onResult(result: Boolean, data: String) {
                        Log.d("test", "获取到COS版本")
                        EventBus.getDefault().post(StateResponse("获取COS版本:" + (if (result) "成功" else "失败") + ",版本:" + data))
                    }
                })

            R.id.create_key
            ->
                Device.createSessionKey(object : DeviceCallback {
                    override fun onResult(result: Boolean, data: String) {
                        Log.d("test", "生成会话秘钥:" + (if (result) "成功" else "失败") + "data:$data")
                        EventBus.getDefault().post(StateResponse("生成回话秘钥:" + if (result) "成功" else "失败"))
                        EventBus.getDefault().post(SharedKeyResponse(data))
                    }
                })
        }
    }

}

 

 

 

你可能感兴趣的:(Android kotlin fragment中使用布局控件)