Activity从入门到放弃

    技术2022-07-10  155

    基本控件 ①Button: 注意到显示的text均为大写,如果要保留原始文字内容,需在XML上添加: android:textAllCaps = "false"

    /点击事件需要在相应Activity中注册监听器

    button.setOnClickListener{ ... }

    ②TextView: 显示文本信息 ③EditText:文本输入框

    android:hint = "text" //提示输入内容 android:maxLines = "n" //规定行数

    ④ImageView / ProgressBar 图片放在drawable目录下 通过style属性可以设置进度条的形式 ⑤AlertDialog 弹出对话框,置顶于所有界面元素之上 setTitle() setMessage() setCancelable(false) :Back键不能返回 setPositiveButton/setNegativeButton(“text”){dialog, which->} 确定按钮和取消按钮

    布局 ①LinearLayout:线性布局(很常用) ②RelativeLayout:相对布局,控件相对于父布局进行定位的。注意多了一些属性。eg:相对于父布局或其它控件的上下左右。 ③FrameLayout:帧布局,最简单,与Fragment相结合RecyclerView(重点介绍) 横向布局,网格布局,瀑布流布局 新增控件需要在build.gradle中添加依赖 同时在activity_main.xml中需要把完整的包路径写出来

    配置适配器:

    class FruitAdapter (val fruitList: List<Fruit>) : RecyclerView.Adapter<FruitAdapter.ViewHolder>(){ inner class ViewHolder(view: View): RecyclerView.ViewHolder(view){ val fruitImage :ImageView = view.findViewById(R.id.fruitImage) val fruitName :TextView = view.findViewById(R.id.fruitName) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view= LayoutInflater.from(parent.context) .inflate(R.layout.fruit_item, parent, false) val viewHolder = ViewHolder(view) //最外层布局 viewHolder.itemView.setOnClickListener { val position = viewHolder.adapterPosition val fruit = fruitList[position] Toast.makeText(parent.context,"You clicked view ${fruit.name}",Toast.LENGTH_SHORT).show() } //ImageView viewHolder.fruitImage.setOnClickListener { val position = viewHolder.adapterPosition val fruit = fruitList[position] Toast.makeText(parent.context,"you clicked image ${fruit.name}", Toast.LENGTH_SHORT).show() } return viewHolder } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val fruit = fruitList[position] holder.fruitImage.setImageResource(fruit.ImageId) holder.fruitName.text = fruit.name } override fun getItemCount() = fruitList.size }

    继承自RecyclerView.Adapter必须重写 onCreateViewHolder():创建ViewHolder实例,将布局加载进来,传入构造函数中 onBindViewHolder():对RecyclerView子项的数据进行赋值,当子项滚动到屏幕内时就会执行 getItemCount():返回数据源的长度即可 ❗相应Activity中需要layoutManager来加载布局

    val layoutManager = StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL) recyclerView.layoutManager = layoutManager val adapter = FruitAdapter(fruitList) recyclerView.adapter = adapter

    Fragment了解了一下平板手机兼容的新闻应用,就不做归纳了(心累~~) 下次就要开始学习第二个组件: BroadcastReceiver!!!

    Processed: 0.043, SQL: 9