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
}
}
  1. 如果编写了数据类(起了一个c++结构体的作用,因为数组只能传递一个),创建对应的List并且赋值
  2. 给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学习笔记——TextView

文本属性设置函数

方法 说明 备注
text 当前文本内容 可以直接赋值,更改内容,可以当做变量,获取内容
textSize 文本大小 Float类型
setTextColor 设置文本颜色 与Color类一起使用
setBackgroundColor 设置背景色 与Color类一起使用
gravity 设置对齐方式 与Gravity一起使用,多种对齐方式用or连接
ellipsize 多余文本的省略方式 与TruncateAt一起使用
setSingleLine 是否单行显示 参数Boolean
isFocusable 是否可获得焦点 可赋值,更改属性,可以取值
isFocusableInTouchMode 是否在触摸时获得焦点 可赋值,更改属性,可以取值

补充

Color

Color类中的常用静态成员

名称 参数 作用
rgb 三个r、g、b值 返回一个对应rgb的Color对象
其他静态成员常量 yellow、green、red、grey等对应颜色的Color对象
阅读更多

Kotlin学习笔记——RadioButton和RadioGroup

RadioButton的使用

拖拽出RadioButton,和RadioGroup,把RadioButton拖到RadioGroup的子部件下

RadioGroup的使用

方法 使用 备注
android:orientation 设置RadioGroup中RadioButton的排列方式 "vertical"为垂直,"horizontal"为水平
setOnCheckedChangeListener 设置选择改变时的操作

特定效果

RadioButton多行多列显示

阅读更多

Kotlin学习笔记——TabLayout

1
#define 小毛驴 xml

使用场景

如果想让ViewPager的tab标签和Toolbar合二为一的话,可以在Toolbar中嵌套TabLayout

使用方法

  1. 编写好小毛驴文件,把TabLayout嵌套到Toolbar中,编写好每一页的小毛驴布局文件,写好传递数据的类
  2. 编写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
class BlankFragment : Fragment() {
var ctx:Context? = null
var mPosition:Int = 0
var mInageId:Int = 0
var mDesc:String = ""
var title:String = ""

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.item, container, false)

val pic:ImageView = view.findViewById(R.id.imageView)
val desc:TextView = view.findViewById(R.id.textView)

pic.setImageResource(mInageId)
desc.text = mDesc
return view
}

companion object {
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
}
}
}
阅读更多

Kotlin学习笔记——anko库

弹出吐司

方法 参数 解释 备注
toast CharSequence 弹出短吐司 相当于Toast.makeText(this, "String", Toast.Toast.LENGTH_SHORT).show()
longToast CharSequence 弹出长吐司 相当于Toast.makeText(this, "String", Toast.Toast.LENGTH_LONG).show()

像素转换方法

方法 说明
dip dip 转 px
sp sp 转 px
px2dip px 转 dip
px2sp px 转 sp
dimen dip 转 sp

弹出警告窗口

1
2
3
4
5
6
7
8
alert("对话框内容", "对话框标题") {
positiveButton("确认") {
//点按确认后执行的操作
}
negativeButton("取消") {
//点按取消后执行的操作
}
}.show()
阅读更多

Kotlin学习笔记——ViewPager

1
#define 小毛驴 xml

使用方法

  1. 在活动页面添加ViewPager,如果需要tab标签,在ViewPager里嵌套PagerTabStrip或PagerTitleStrip
  2. 设计传送数据的类(一张图和一个标题就足够)
  3. 编写ViewPager的适配器
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
class ImagePagerAdapter(val context: Context, val itemList:MutableList<itemInfo>) : PagerAdapter() {
val views = mutableListOf<ImageView>()
init {
for (item in itemList) {
val view = ImageView(context)
//view.layoutParams = ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT)
view.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)

view.setImageResource(item.pic)
view.scaleType = ImageView.ScaleType.FIT_CENTER
views.add(view)
}
}
override fun isViewFromObject(p0: View, p1: Any): Boolean = (p0 === p1)

override fun getCount(): Int = views.size

override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(views[position])
}

override fun instantiateItem(container: ViewGroup, position: Int): Any {
container.addView(views[position])
return views[position]
}

override fun getPageTitle(position: Int): CharSequence? {
return itemList[position].desc
}//与PagerTabStrip或配合使用

}
  1. 给PagerView添加适配器和页面改变的Listener
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
class MainActivity : AppCompatActivity(), ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(p0: Int) {
}

override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {

}


override fun onPageSelected(p0: Int) {
Toast.makeText(this, p0.toString(), Toast.LENGTH_SHORT).show()
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//supportActionBar?.hide()
var vp:ViewPager = findViewById(R.id.vp)
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]))
}
vp.adapter = ImagePagerAdapter(this, list)
vp.currentItem = 0
vp.addOnPageChangeListener(this)

var title: PagerTabStrip = findViewById(R.id.title)

title.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
title.setTextColor(Color.RED)
}
}
阅读更多

Kotlin学习笔记——lambda

参考文献——kotlin之Lambda编程
来自简书作者——程自舟

Kotlin lambda语法

1
2
3
4
5
6
7
8
9
10
11
12
13
btn.setOnClickListener ((View v) -> {
toast("click")
})
btn.setOnclickListener {
toast("click")
}
btn.setOnLongClickListener {
toast("Long Click")
true//lambdda的返回值,不写return
}
{a:Int, b:String -> String
(a + b.toDouble()).toString()
}

完整写法

1
2
3
4
5
6
7
8
9
{a:Int, b:String, c:Long/*输入参数列表*/ -> String/*返回值类型*/
/*lambda body*/
var temp:Double = a + b.toDouble()
if (c == 0L) {
"error"
} else {
(temp.toDouble() + c).toString()
}//返回值(不要写return)
}

省略参数的写法

阅读更多

Kotlin学习笔记——基础语法篇之函数

函数的一般形式

1
2
3
4
5
fun mathodName(/*para list*/) : String/*return value type*/ {
/*
function body
*/
}

与C、C++或java的不同

  1. 如果要重载,在fun前面加override
  2. 如果想让子类重载,要加open关键词(类也一样)
  3. 可以定义全局函数,函数不是必须写在类里
  4. 可以有默认参数,且默认参数不必放在最后几个
1
2
3
4
5
6
7
8
9
10
11
12
fun TextView.println(str:CharSequence) {
append("\n${str}")
}
fun TextView.print(str:CharSequence) {
append(str)
}//这个东西是扩展函数,后面说
fun func(str:String = "哈哈哈",i:Int, j:Double) {//str的默认参数"哈哈哈"
val text:TextView = findViewById(R.id.text)
text.print("$str")
text.println("$i")
text.println("$j")
}
  • 此时,在调用时,如果第一个不采用默认参数,则按照顺序传递三个参数,否则按照以下形式传递参数
阅读更多

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会自动滑到末尾
阅读更多

Kotlin学习笔记——基础语法篇之数据类型

一、基本数据类型

Kotlin的数据类型

数据类型名称 Kotlin的数据类型
整型 Int
长整型 Long
浮点型 Float
双精度浮点型 Double
布尔型 Boolean

声明变量

1
2
3
4
5
6
7
8
9
10
11
var integer:Int//一般用法var/val + 标识符 + : + 类型名,var表示变量
val integer1:Int = 0//val表示常量,相当于java中的final,c++中的const
var str = "this is a string"
//没有":String",此时只要保证编译器可以知道变量的类型,则编译器可以完成类型推断
var flt:Float = 5f//f表示数据为float类型
var tobar:Toolbar? = findViewById<Toolbar>(R.id.toolbar)
/*
类型名后+'?'表示该变量为可空变量,kotlin为了防止java中NullPointerException,
默认所有的变量都是不可空(不能为null的),如果要让变量为空,需要+'?',
此时,编译器会强制程序员对所有可空变量进行非空判断
*/

Kotlin的类型转换

阅读更多