Kotlin笔记(1-3)

  1. kotlin接口的方法可以实现

     interface ToolBarManager {
         val toolbar:Toolbar
    
         fun initMainToolBar(){
             toolbar.setTitle("Ivan影音")
         }
     }
    
  2. 惰性加载,初始化toolbar

     class MainActivity : BaseActivity() ,ToolBarManager{
         override val toolbar by lazy { find(R.id.toolbar) }
    
         override fun getLayoutId(): Int {
           return R.layout.activity_main
         }
    
     }
    
  3. 给toolbar添加设置按钮

     //接口的方法也可以有方法体
     fun initMainToolBar(){
         toolbar.setTitle("Ivan影音")
         toolbar.inflateMenu(R.menu.main)
     }
    
     //xml
     
     
         
     
    
  4. 给toolbar设置点击事件

     //方式一
    toolbar.setOnMenuItemClickListener {
        when(it.itemId){
            R.id.settings->toolbar.context.startActivity(Intent(toolbar.context,SettingsActivity::class.java))
        }
        true
    }

    //方式二
    toolbar.setOnMenuItemClickListener { item ->
        when(item?.itemId){
            R.id.settings->{
                Toast.makeText(toolbar.context,"设置",Toast.LENGTH_SHORT).show()
            }
        }
        true
    }
  1. 跳转设置界面

     //跳转到设置界面
     toolbar.context.startActivity(Intent(toolbar.context,SettingsActivity::class.java))
    
  2. 使用PreferenceFragment

     //1.创建fragment
     class SettingsFragment:PreferenceFragment() {
         override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
             //设置布局
             addPreferencesFromResource(R.xml.setting)
             return super.onCreateView(inflater, container, savedInstanceState)
         }
     }
    
     //2. 创建xml布局
     
     
    
         
         
         
         
     
    
     //3. 在activity中引入
      
    
     //4. 获取状态
     val sp = PreferenceManager.getDefaultSharedPreferences(this)
     val push = sp.getBoolean("push", false)
     println("push = "+push)
    
    
     //点击事件,重写onPreferenceTreeClick
     override fun onPreferenceTreeClick(preferenceScreen: PreferenceScreen?, preference: Preference?): Boolean {
         val key = preference?.key
         if ("about_app".equals(key)){
             toast("点击了关于")
         }
         return super.onPreferenceTreeClick(preferenceScreen, preference)
     }
    
  3. kotlin 单例模式

     class FragmentUtils private constructor(){ //私有构造方法
         companion object {
             val fragmentUtils by lazy { FragmentUtils() }
         }
     }
    
  4. fragment单例容器

     class FragmentUtils private constructor() { //私有构造方法
    
         val homeFragment by lazy { HomeFragment() }
         val mvFragment by lazy { MvFragment() }
         val vBangFragment by lazy { VBangFragment() }
         val yueDanFragment by lazy { YueDanFragment() }
    
         companion object {
             val fragmentUtils by lazy { FragmentUtils() }
         }
    
         /**
          * 获取fragment
          */
         fun getFragment(tabId: Int): BaseFragment? {
             when (tabId) {
                 R.id.tab_home -> return homeFragment
                 R.id.tab_mv -> return mvFragment
                 R.id.tab_vbang -> return vBangFragment
                 R.id.tab_yuedan -> return yueDanFragment
             }
             return null
         }
     }
    
  5. bottombar的切换

     bottomBar.setOnTabSelectListener {
         val transaction = supportFragmentManager.beginTransaction()
         transaction.replace(R.id.fl_main,FragmentUtils.fragmentUtils.getFragment(it),it.toString())
         transaction.commit()
     }
    
  6. cardview的使用

    
    
  7. okhttp3联网获取数据

    /**
     * 获取首页数据
     */
    private fun loadDatas() {
        val path = URLProviderUtils.getHomeUrl(0, 20)
        val request = Request.Builder()
                .get()
                .url(path)
                .build()
        OkHttpClient().newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                myToast("请求失败:" + Thread.currentThread().name)
                
            }
    
            override fun onResponse(call: Call?, response: Response?) {
                myToast("请求成功:" + Thread.currentThread().name)
                val result = response?.body()?.string()
                println("result = $result")
            }
        })
    }
    
  8. 解析网络数据

    override fun onResponse(call: Call?, response: Response?) {
        myToast("请求成功:" + Thread.currentThread().name)
        val result = response?.body()?.string()
        LogUtil.json(result, "请求成功:")
    
        val gson = Gson()
        //这个写法  有点复杂
        val list = gson.fromJson>(result, object : TypeToken>() {}.type)
    }
    
  9. 线程切换工具类

    object ThreadUtil {
        val handler = Handler(Looper.getMainLooper())
    
        /**
         * 运行到主线程
         */
        fun runOnUiThread(runnable: Runnable){
            handler.post(runnable)
        }
    }
    
  10. 下拉刷新

    //初始化刷新控件
    refreshLayout.setColorSchemeColors(Color.RED,Color.YELLOW,Color.GREEN)
    refreshLayout.setOnRefreshListener {
        loadDatas()
    }
    
    //网络请求成功或者失败后,隐藏刷新控件
    refreshLayout.isRefreshing = false
    
  11. 自定义加载更多

    一:布局处理
        1.最后一条作为加载更多
            override fun getItemCount(): Int {
                return list.size + 1
            }
        2. 位置和类型的一一对应
             override fun getItemViewType(position: Int): Int {
                if (position == list.size) {
                    //加载更多
                    return 1
                } else {
                    //普通布局
                    return 0
                }
            }
        3. 根据类型创建两种布局
             override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeHolder {
                if (viewType == 1){
                    return HomeHolder(LoadMoreView(parent.context))
                }else{
                    return HomeHolder(HomeItemView(parent.context))
                }
            }
        4. 绑定数据的时候需要判断
            override fun onBindViewHolder(holder: HomeHolder, position: Int) {
                //如果是最后一条,加载更多,则不需要绑定数据
                if (position == list.size)return
                 ... //正常位置数据绑定 省略
            }
    
    二: 监听recyclerview滑动,当处于空闲,并且滑动到最后一条时,开始加载更多
    代码实现:
    //滑动监听-加载更多
    recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
            //如果是空闲状态
            if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                val layoutManager = recyclerView?.layoutManager
                //如果是线性布局
                if (layoutManager is LinearLayoutManager) {
                    val manager: LinearLayoutManager = layoutManager
                    val lastPos = manager.findLastVisibleItemPosition()
                    //判断是否滑动到最后一条
                    if (lastPos == homeAdapter.itemCount - 1) {
                        loadMore(homeAdapter.itemCount - 1)
                    }
                }
            }
        }
    })
    

你可能感兴趣的:(Kotlin笔记(1-3))