Kotlin学习笔记——BroadCast

1
#define 小毛驴 xml

收发广播

使用场景:Fragment想要向外传递信息

  1. 在Fragment中发送广播
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    class BlankFragment : Fragment() {
    var ctx:Context? = null
    var mPosition:Int = 0
    var mInageId:Int = 0
    var mDesc:String = ""
    var title:String = ""

    val colorNames = listOf<String>("红色","黄色","绿色","青色","蓝色")
    val colors = intArrayOf(Color.RED, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE)
    var mSeq:Int = 0
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    ctx = activity
    if (arguments != null) {
    mPosition = arguments!!.getInt("position", 0)
    mInageId = arguments!!.getInt("image_id", 0)
    mDesc = arguments!!.getString("desc")
    title = arguments!!.getString("title")
    }
    val view = inflater.inflate(R.layout.show_info, container, false)

    view.findViewById<ImageView>(R.id.imageView).setImageResource(mInageId)
    view.findViewById<TextView>(R.id.textView).text = mDesc
    view.findViewById<Button>(R.id.se).setOnClickListener {
    ctx!!.selector("选择颜色", colorNames) {
    mSeq = it

    val intent = Intent(BlankFragment.EVENT)
    intent.putExtra("seq", it)
    intent.putExtra("color", colors[it])
    ctx!!.sendBroadcast(intent)//发送广播
    }
    }
    return view
    }

    companion object {
    const val EVENT:String = "changeColor"//const,编译期常量
    fun newInstance(position:Int, image_id:Int, desc:String, title:String) : BlankFragment {

    val fragment = BlankFragment()
    val bundle = Bundle()
    bundle.putInt("position", position)
    bundle.putInt("image_id", image_id)
    bundle.putString("desc", desc)
    bundle.putString("title", title)
    fragment.arguments = bundle
    return fragment
    }
    }
    }
  2. 在要接收广播的页面注册receiver
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    class MainActivity : FragmentActivity(){
    private var BGChangeRecever:myBgChangeRecever? = null
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var vp:ViewPager = findViewById(R.id.vp)
    var title: PagerTabStrip = findViewById(R.id.title)

    val pics = arrayOf(R.mipmap.basic, R.mipmap.close, R.mipmap.debug, R.mipmap.edit)
    val list:MutableList<itemInfo> = mutableListOf()
    for (i in pics.indices) {
    list.add(itemInfo((i+1).toString(), pics[i], ((i+1)*(i+1)).toString()))
    }
    vp.adapter = infoPagerAdapter(supportFragmentManager, list)
    vp.currentItem = 0
    }

    public override fun onStart() {
    super.onStart()
    BGChangeRecever = myBgChangeRecever()

    val filiter = IntentFilter(BlankFragment.EVENT)//广播过滤器,过滤掉参数以外的广播
    registerReceiver(BGChangeRecever,filiter)//开始时注册接收器

    }

    public override fun onStop() {
    unregisterReceiver(BGChangeRecever)//结束前注销接收器
    super.onStop()
    }

    private inner class myBgChangeRecever : BroadcastReceiver() {//广播接收器
    override fun onReceive(context: Context?, intent: Intent?) {//接收广播后执行的操作
    if (intent != null) {
    val color = intent.getIntExtra("color", Color.GREEN)
    textView2.setTextColor(color)
    }
    }

    }
    }

接收系统广播

静态注册

阅读更多

Kotlin学习笔记——Button

实现短按长按的方法

调用函数

方法 参数 参数解释 返回值 备注
setOnClickListener lambda表达式 lambda的参数为发生点击动作的View,返回值Unit Unit 相当于override fun onClickListener(v:View)
setOnLongClickListener lambda表达式 lambda的参数为发生点击动作的View,返回值Boolean(true表示这个事件已经消耗完了,false表示事件继续传递,会触发一次短按事件) Unit 相当于override fun onLongClick(v:View):Boolean

例子

1
2
3
4
5
6
7
btn.setOnClickListener {
toast("click")
}
btn.setOnLongClickListener {
toast("Long Click")
true
}

使用内部类

阅读更多

Kotlin学习笔记——Fragment

1
#define 小毛驴 xml

使用方法

Fragment与ViewPager搭配,实现翻页,实现每页多个控件

  1. 写好每个item的小毛驴文件和数据传送类
  2. 继承Fragment类,自定义一个fragment
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    class BlankFragment : Fragment() {
    var ctx:Context? = null
    var mPosition:Int = 0
    var mInageId:Int = 0
    var mDesc:String = ""
    var title:String = ""

    val colorNames = listOf<String>("红色","黄色","绿色","青色","蓝色")
    val colors = intArrayOf(Color.RED, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE)
    var mSeq:Int = 0
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    ctx = activity
    if (arguments != null) {
    mPosition = arguments!!.getInt("position", 0)
    mInageId = arguments!!.getInt("image_id", 0)
    mDesc = arguments!!.getString("desc")
    title = arguments!!.getString("title")
    }//获取数据
    val view = inflater.inflate(R.layout.show_info, container, false)

    view.findViewById<ImageView>(R.id.imageView).setImageResource(mInageId)
    view.findViewById<TextView>(R.id.textView).text = mDesc
    //显示数据
    return view
    }

    companion object {
    fun newInstance(position:Int, image_id:Int, desc:String, title:String) : BlankFragment {//调用这个函数,创建新的fragment

    val fragment = BlankFragment()
    val bundle = Bundle()
    bundle.putInt("position", position)
    bundle.putInt("image_id", image_id)
    bundle.putString("desc", desc)
    bundle.putString("title", title)
    fragment.arguments = bundle
    return fragment
    }
    }
    }
  3. ViewPager的适配器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class infoPagerAdapter(val fragManger: FragmentManager, val itemList:MutableList<itemInfo>) : FragmentStatePagerAdapter(fragManger) {
    override fun getCount(): Int = itemList.size
    override fun getItem(p0: Int): Fragment {
    val item = itemList[p0]
    return BlankFragment.newInstance(p0, item.pic, item.desc, item.name)
    }

    override fun getPageTitle(position: Int): CharSequence? {
    return itemList[position].name
    }
    }
    4.给ViewPager添加适配器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class MainActivity : FragmentActivity(){
    //这个时候,继承的是FragmentActivity
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var vp:ViewPager = findViewById(R.id.vp)
    var title: PagerTabStrip = findViewById(R.id.title)
    val list:MutableList<itemInfo> = mutableListOf()
    //省略中间给list赋值的过程
    vp.adapter = infoPagerAdapter(supportFragmentManager, list)
    vp.currentItem = 0
    }
    }

Kotlin学习笔记——GridView

Kotlin学习笔记——GridView

1
#define 小毛驴 xml

使用方法

  1. 设计好界面
  2. 新建一个小毛驴文件,这个小毛驴文件是GridView中,每一个Item的界面布局文件
  3. (可选)编写一个数据类,用来保存每个item中的数据,用data class可以很方便
  4. 编写一个继承BaseAdapter适配器的类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    class GridAdapter(private val context: Context, private val strList:MutableList<myItems>, private val background:Int) : BaseAdapter() {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    var view = convertView
    val holder:ViewHolder
    if (convertView == null) {
    view = LayoutInflater.from(context).inflate(R.layout.item, null)
    //我猜这个函数的作用是指定这个类所对应的小毛驴文件
    holder = ViewHolder()
    holder.myLayout = view.findViewById<LinearLayout>(R.id.all)
    holder.desc = view.findViewById<TextView>(R.id.textView)
    holder.pic = view.findViewById<ImageView>(R.id.imageView)
    view.tag = holder
    } else {
    holder = (view?.tag) as ViewHolder
    }
    //以上是固定格式
    val myItem = strList[position]
    //传进来的数据数组,适配器根据数组大小反复调用这个函数构造ViewList
    //position是当前位置,对应数组下标
    //holder.myLayout.setBackgroundColor(background)
    holder.desc.text = myItem.desc
    holder.pic.setImageResource(myItem.image)
    //以上是自定义每个控件的显示内容
    return view!!
    }

    override fun getItem(position: Int): Any = strList[position]
    override fun getItemId(position: Int): Long = position.toLong()
    override fun getCount(): Int = strList.size

    inner class ViewHolder {
    lateinit var myLayout:LinearLayout
    lateinit var desc: TextView
    lateinit var pic: ImageView
    }
    }
  5. 如果编写了数据类(起了一个c++结构体的作用,因为数组只能传递一个),创建对应的List并且赋值
  6. 给GridView添加适配器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    var grid:GridView = findViewById(R.id.panel)
    var pics = arrayOf(R.mipmap.a, R.mipmap.b, R.mipmap.c, R.mipmap.d, R.mipmap.e, R.mipmap.f, R.mipmap.g, R.mipmap.h)
    var descs = arrayOf("超级大帅哥刘甜甜", "刘甜甜最喜欢的大明星周周", "刘甜甜最喜欢的性感裸男", "刘甜甜最想养的橘猫", "还是超级大帅哥刘甜甜", "刘甜甜最喜欢的动画人物米奇", "还是刘甜甜最喜欢的动画人物米奇", "用来凑数的发际线哥")
    var data:MutableList<myItems> = mutableListOf()
    for (i in pics.indices) {
    data.add(myItems(descs[i], pics[i]))
    }
    grid.adapter = GridAdapter(this, data, Color.GRAY)
    grid.numColumns = 2//设置列数

Kotlin学习笔记——ListView

1
#define 小毛驴 xml

使用方法

  1. 设计好界面
  2. 新建一个小毛驴文件,这个小毛驴文件是ListView中,每一个Item的界面布局文件
  3. (可选)编写一个数据类,用来保存每个item中的数据,用data class可以很方便
  4. 编写一个继承BaseAdapter适配器的类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    class ListViewAdapter(private val context: Context, private val strList:MutableList<myItems>, private val background:Int) : BaseAdapter() {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
    var view = convertView
    val holder:ViewHolder
    if (convertView == null) {
    view = LayoutInflater.from(context).inflate(R.layout.item, null)
    //我猜这个函数的作用是指定这个类所对应的小毛驴文件
    holder = ViewHolder()
    holder.ll_item = view.findViewById<LinearLayout>(R.id.ll_item)
    holder.iv_icon = view.findViewById<ImageView>(R.id.iv_icon)
    holder.tv_name = view.findViewById<TextView>(R.id.tv_name)
    holder.tv_desc = view.findViewById<TextView>(R.id.tv_desc)
    view.tag = holder
    } else {
    holder = (view?.tag) as ViewHolder
    }
    //以上是固定格式
    val myItem = strList[position]
    //传进来的数据数组,适配器根据数组大小反复调用这个函数构造ViewList
    //position是当前位置,对应数组下标
    holder.ll_item.setBackgroundColor(background)
    holder.iv_icon.setImageResource(myItem.image)
    holder.tv_name.text = myItem.name
    holder.tv_desc.text = myItem.desc
    //以上是自定义每个控件的显示内容,根据之前传进来的List里面的数据
    return view!!
    }

    override fun getItem(position: Int): Any = strList[position]
    override fun getItemId(position: Int): Long = position.toLong()
    override fun getCount(): Int = strList.size

    inner class ViewHolder {
    lateinit var ll_item:LinearLayout
    lateinit var iv_icon:ImageView
    lateinit var tv_name:TextView
    lateinit var tv_desc:TextView
    }
    }
  5. 如果编写了数据类(起了一个c++结构体的作用,因为数组只能传递一个),创建对应的List并且赋值
  6. 给ListView添加适配器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    var item:MutableList<myItems> = mutableListOf()
    val imageIds = arrayOf(R.mipmap.a, R.mipmap.b, R.mipmap.c, R.mipmap.d, R.mipmap.e)
    var name = arrayOf("超级大帅哥刘甜甜", "还是超级大帅哥刘甜甜", "可爱的橘猫", "性感裸男","周周")
    var desc = arrayOf("是他是他就是他,我们的大帅哥,刘天天", "是他是他还是他,我们的大帅哥,刘天天", "刘天天最想养的橘猫", "刘天天最喜欢的性感裸男","刘天天最喜欢的大明星周周")
    //各种数据
    setContentView(R.layout.activity_clickhere)
    for (i in imageIds.indices) {
    item.add(myItems(name[i], desc[i], imageIds[i]))
    }
    //初始化要传递的List

    var list:ListView = findViewById<ListView>(R.id.list)
    list.adapter = ListViewAdapter(this,item ,Color.WHITE)//你刚才自己写的适配器类
    //为ListView添加适配器

Kotlin学习笔记——EditText

输入监听器

方便起见,在activity的内部写一个内部类,用来监听输入

编写监听器

1
2
3
4
5
6
7
8
9
10
11
inner class EditWatcher : TextWatcher {
override fun afterTextChanged(s:Editable) {

}
override fun beforeTextChanged(s:CharSequence, start:Int, count:Int, after:Int) {

}
override fun onTextChanged(s:CharSequence, start:Int, count:Int, after:Int) {

}
}

注意

  1. 把Editable直接toString()就是用户当前的输入
阅读更多

Kotlin学习笔记——Spinner

android提供的spinner

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MainActivity : AppCompatActivity() {
val strs = arrayOf("1", "2","3","4","5", "6", "7","8","9","10","11","12","13","14","15","16")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val sp = findViewById<View>(R.id.spinner) as Spinner
val startAdapter = ArrayAdapter(this, R.layout.support_simple_spinner_dropdown_item, strs)
startAdapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item)
sp.prompt = "请选择"
sp.adapter = startAdapter
sp.setSelection(0)
var listen = myItemClickListener()
sp.onItemSelectedListener = listen
}
internal inner class myItemClickListener : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {

}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
toast("你的选择是:${strs[position]}")
}
}
}

步骤

  1. 一个ArrayAdapter,参数分别是thisR.layout.support_simple_spinner_dropdown_itemArray<String>(到时候的item)
  2. 刚才的ArrayAdapter设置效率视窗资源,调用setDropDownViewResource函数,参数是R.layout.support_simple_spinner_dropdown_item
  3. ArrayAdapter赋值给spinneradapter成员
  4. 设置默认选项,setSelection
  5. 如果想让spinner为对话框形式的,在xml文件中设置android:spinnerMode="Dialog",spinnerprompt成员为设置对话框标题的接口
  6. 新建一个内部类,监听下拉选择,继承AdapterView.OnItemSelectedListener,重载onNothingSelectedonItemSelected两个方法
  7. 新建监听器对象,通过spinneronItemSelectedListener设置为监听器

anko库提供的spinner——selector

1
2
3
4
5
6
7
val strs = Arrayof("1", "2", "3")
aTextView.text = "假装这是一个spinner,其实我是TextView"
aTextView.setOnClickListener {
selector("请选择", strs) { i ->
toast("你的选择是:${strs[i]}")
}
}
阅读更多

Kotlin学习笔记——RecyclerView

1
#define 小毛驴 xml

布局管理器

LinearLayoutManager

类似于线性布局

构造
(Context context)
(Context context,int orientation,boolean reverseLayout)
(Context context, AttributeSet attrs, int defStyleAttr,int defStyleRes)
参数 解释
Context context 上下文,初始化时,构造方法内部加载资源用
int orientation 方向,垂直和水平,默认为垂直
boolean reverseLayout 是否倒序,设置为True,从最后一个item开始,倒序加载。此时,RecyclerView第一个item是添加进Adapter中的最后一个,最后一个item是第一个加进Adapter的数据,RecyclerView会自动滑到末尾
阅读更多