喜提假期 ^_^
把考试周摸鱼看的一些基础知识汇总一下吧~
TextView
属性 |
作用 |
备注 |
text |
文本内容 |
文字默认是左上角对齐的 |
gravity |
指定文字的对齐方式 |
可选值:top、bottom、start、end、center |
textColor |
文本颜色 |
参数为色彩的十六进制表示,如 #FFB6C1 |
textSize |
文本大小 |
参数如 24sp ,使用sp作为单位,可随系统设置改变大小 |
1 2 3 4 5 6 7 8
| <TextView android:id="@+id/my_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="This is TextView" android:gravity="center" android:textColor="#00ff00" android:textSize="24sp"/>
|
一个简单的栗子:
1 2 3 4 5 6
| <Button android:id="@+id/my_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Button" android:textAllCaps="true"/>
|
由于Android系统默认会将按钮上的英文字母全部转换为大写,所以要用到textAllCaps
属性来取消默认大写
为按钮添加监听,实现Activity的跳转:
1 2 3 4
| my_button.setOnClickListener{ val intent = Intent(this,Main2Activity::class.java) startActivity(intent) }
|
EditText
一个输入框,允许用户在控件里输入和编辑内容,并能在程序中对这些内容进行处理。
一个简单的例子:
1 2 3 4 5 6 7
| <EditText android:id="@+id/my_edit_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="这是提示性文本" android:maxLines="2" />
|
maxLines
:例子中表示此控件最多两行内容,超过两行文本向上滚动
获取输入框内的内容,并用Toast显示获取的内容:
1 2 3 4
| my_button.setOnClickListener{ val value = my_edit_text.text.toString() Toast.makeText(this,value,Toast.LENGTH_SHORT).show() }
|
ImageView
顾名思义,用来显示图片的控件:
1 2 3 4 5
| <ImageView android:id="@+id/my_imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@mipmap/ic_launcher"/>
|
src
:用来指明图片的位置,这里表示mipmap
目录下的ic_launcher.png
文件
可以调用ImageView
的setImageResource()
方法改变图片资源:
1 2 3 4
| my_button.setOnClickListener{ my_imageView.setImageResource(R.mipmap.ic_launcher_round) }
|
ProgressBar
用于在界面上显示一个进度条,表示程序正在加载一些数据
属性 |
作用 |
参数 |
visibility |
控件是否可见 |
visible:可见 & invisible:不可见 & gone:不可见且不占用屏幕空间 |
style |
设置进度条样式 |
如水平进度条:style="@style/Widget.AppCompat.ProgressBar.Horizontal" |
max |
设置水平进度条的最大值 |
- |
一个水平进度条栗子:
1 2 3 4 5
| <ProgressBar android:layout_width="match_parent" android:layout_height="wrap_content" style="@style/Widget.AppCompat.ProgressBar.Horizontal" android:max="100"/>
|
可以在代码中动态的更改进度条的进度,比如每点击一次按钮,进度条就向前移动十分之一:
1 2 3
| my_button.setOnClickListener{ my_progressBar.progress += 10; }
|
同时,我们还可以通过点击按钮改变进度条的可见性:
1 2 3 4 5 6 7
| my_button.setOnClickListener{ if(my_progressBar.visibility == View.VISIBLE){ my_progressBar.visibility = View.GONE }else{ my_progressBar.visibility = View.VISIBLE } }
|
setVisibility()
方法允许传入View.VISIBLE
&View.INVISIBLE
&View.GONE
三种值
AlertDialog
用于在当前界面弹出一个对话框:
1 2 3 4 5 6 7 8 9 10 11 12
| AlertDialog.Builder(this).apply { setTitle("This is Title") setMessage("Something") setCancelable(false) setPositiveButton("OK"){ dialog, which -> } setNegativeButton("Cancel"){ dialog, which -> } show() }
|