-
kotlin接口的方法可以实现
interface ToolBarManager { val toolbar:Toolbar fun initMainToolBar(){ toolbar.setTitle("Ivan影音") } }
-
惰性加载,初始化toolbar
class MainActivity : BaseActivity() ,ToolBarManager{ override val toolbar by lazy { find<Toolbar>(R.id.toolbar) } override fun getLayoutId(): Int { return R.layout.activity_main } }
-
给toolbar添加设置按钮
//接口的方法也可以有方法体 fun initMainToolBar(){ toolbar.setTitle("Ivan影音") toolbar.inflateMenu(R.menu.main) } //xml <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/main" android:title="设置" app:showAsAction="always" android:icon="@mipmap/ic_settings_white_18dp"/> </menu>
-
给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
}
-
跳转设置界面
//跳转到设置界面 toolbar.context.startActivity(Intent(toolbar.context,SettingsActivity::class.java))
-
使用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布局 <?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <Preference android:key="clear_cache" android:title="清理缓存"/> <SwitchPreference android:key="push" android:title="推送通知"/> <SwitchPreference android:key="load_pic_no_wifi" android:title="非WIFI加载图片"/> <Preference android:key="about_app" android:title="关于APP"/> </PreferenceScreen> //3. 在activity中引入 <fragment android:id="@+id/setting_fragment" class="com.onepontech.ivan.kotlinplayer.ui.fragment.SettingsFragment" android:layout_width="match_parent" android:layout_height="match_parent"/> //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) }
-
kotlin 单例模式
class FragmentUtils private constructor(){ //私有构造方法 companion object { val fragmentUtils by lazy { FragmentUtils() } } }
-
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 } }
-
bottombar的切换
bottomBar.setOnTabSelectListener { val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.fl_main,FragmentUtils.fragmentUtils.getFragment(it),it.toString()) transaction.commit() }
-
cardview的使用
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" app:cardElevation="5dp" app:cardUseCompatPadding="true" app:cardCornerRadius="5dp">
-
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") } }) }
-
解析网络数据
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<List<HomeItemBean>>(result, object : TypeToken<List<HomeItemBean>>() {}.type) }
-
线程切换工具类
object ThreadUtil { val handler = Handler(Looper.getMainLooper()) /** * 运行到主线程 */ fun runOnUiThread(runnable: Runnable){ handler.post(runnable) } }
-
下拉刷新
//初始化刷新控件 refreshLayout.setColorSchemeColors(Color.RED,Color.YELLOW,Color.GREEN) refreshLayout.setOnRefreshListener { loadDatas() } //网络请求成功或者失败后,隐藏刷新控件 refreshLayout.isRefreshing = false
-
自定义加载更多
一:布局处理 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) } } } } })
网友评论