Android app开发学习笔记——Android控件
初级控件
一、TextView(文本视图)
首先这是一个在firt.latout.xml文件中的操作
笔记内容基于约束布局(初始默认给我们的布局)
1.设置长宽
第一种是设置相对高度和宽度
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content" />
这里match_parent代表的是和父类(比如这里的父类指的是整个屏幕的大小)的宽度长度一样长
wrap_content代表的是和内容的长度一样长
第二种是设置绝对高度和宽度
<TextView
android:id="@+id/first_TextView"
android:layout_width="400dp"
android:layout_height="25dp"/>
dp是Android中的一种长度单位
如果设置表示长度、高度等属性时可以使用 dp 或 sp,但如果设置字体,需要使用 sp。
详细可以参考文章: Android开发中的长度单位详解.
2.设置背景
Android中设置背景颜色
加入代码android:background="@color/your_color"
其中your_color是在colors中定义好的颜色,设置格式见后文中的图片
<TextView
android:id="@+id/first_TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/浅蓝"/>
我们可以使用系统已经存在的颜色,也可以通过修改res/values/color.xml文件下的代码来自定义颜色来使用,比如这里的浅蓝就是我自定义的颜色
自定义颜色可以参考XML中的颜色配置
Android中设置背景图片
代码改为andriod:background = "@drawable/your_image"
同理在res/drawable/中加入你想要设置的背景即可
3.设置文本内容及相关属性
<TextView
android:id="@+id/first_TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/浅蓝"
android:text="我是一行文字,皮一下就很开心!哈哈哈哈"
android:textSize="17sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.45"
/>
text的内容就是显示的内容
textSize就是文字的大小sp是字体的大小单位,上文已经介绍过
后面一排app开头的语句就是用于说明约束布局中文本框的位置
先后两个数字表示文本框左上角相对父类的比例位置
代码的显示如下
相关属性
//文本文字
android:text="@string/hello_world" //两种方式,直接具体文本或者引用values下面的string.xml里面的元素
//字体大小
android:textSize="24sp" //以sp为单位
//字体颜色
android:textColor="#0000FF" //RGB颜色
//字体格式
android:textStyle="normal" //normal,bold,italic分别为正常,加粗以及斜体,默认为normal
//文本显示位置
android:gravity="center" //来指定文字的对齐方式,可选值有 top、bottom、left、right、center 等
//是否只在一行内显示全部内容
android:singleLine="true" //true或者false,默认为false
4.在程序(对应的.activity文件)中动态赋值
第一种是直接赋值
TextView textfuzhi=(TextView)findViewById(R.id.first_TextView);
textfuzhi.setText("这里的textfuzhi是我定的变量");
第二种是间接赋值
这种方法显然方便调用
举个栗子
(1)在string.xml中加入
<string name="test">%1$d个不错,%2$d个不错</string>`
(2)在java代码中加入
TextView textfuzhi=(TextView)findViewById(R.id.first_TextView);
textfuzhi.setText(getString(R.string.test,1,2));
更多使用方法可以参考
Android之string.xml 使用总结
Android TextView如何显示Html
5.设置textview点击效果
在Java代码中写入如下内容
里面的setOnclickListener是点击监听器
Toast是输出弹出消息
TextView textfuzhi=(TextView)findViewById(R.id.first_TextView);
textfuzhi.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(Firstactivity.this,"你点到我了",Toast.LENGTH_SHORT).show();
}
});
6.其他属性
//文字加粗bold italic normal
android:textStyle="bold" 黑体
android:ellipsize = "end" //省略号在结尾
android:ellipsize = "start" //省略号在开头
android:ellipsize = "middle" // 省略号在中间
android:ellipsize = "marquee" //跑马灯
android:shadowColor ://阴影颜色
android:shadowDx ://阴影x方向位移
android:shadowDy ://阴影y方向位移
android:shadowRadius ://阴影的半径
//注意:实现跑马灯,必须让该控件获得焦点。
//textView显示文字加图片
android:drawableLeft="@drawable/image1"
android:drawablePadding="10dp"
drawableBottom: 在文本框底端绘制图像
drawableLeft: 在文本框左绘制图像
drawableRight: 在文本框右低绘制图像
drawableTop: 在文本框上端绘制图像
drawablePadding: 设置文本框与图像之间的距离
//Spannable的使用(实现字符串各种风格)
setSpan四个参数.参数1表示格式,参数2表示开始index,参数3表示结尾index,参数4是一个常量,有4种
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
Spannable.SPAN_EXCLUSIVE_INCLUSIVE
Spannable.SPAN_INCLUSIVE_EXCLUSIVE
Spannable.SPAN_INCLUSIVE_INCLUSIVE
如
SpannableString spannableString = new SpannableString("TextViewd的Span使用方法");
BackgroundColorSpan backgroundColorSpan =new BackgroundColorSpan(Color.RED);
spannableString.setSpan(backgroundColorSpan,0,10,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textfuzhi.setText(spannableString);
//还可以把设置背景改成设置点击事件
SpannableString spannableString = new SpannableString("TextViewd的Span使用方法");
BackgroundColorSpan backgroundColorSpan =new BackgroundColorSpan(Color.RED);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
Toast.makeText(Firstactivity.this,"你点到我了",Toast.LENGTH_SHORT).show();
}
};
spannableString.setSpan(backgroundColorSpan,0,10,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableString.setSpan(clickableSpan,0,10,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textfuzhi.setMovementMethod(LinkMovementMethod.getInstance());
textfuzhi.setText(spannableString);
Button button1 =(Button)findViewById(R.id.Button_1);
//跑马灯效果
<TextView
android:id="@+id/first_TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/浅蓝"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"//循环次数无限
android:scrollHorizontally="true"//让文字可以水平滑动
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"//把文字限制在一行
android:text="我是一行文字,皮一下就很开心!哈哈哈哈!我是一行文字,皮一下就很开心!哈哈哈哈!我是一行文字,皮一下就很开心!哈哈哈哈!"
android:textSize="17sp"/>
二、Button(按钮)
首先该模块和TextView一样具有 text,textcolor,backgroud 等属性,并对应setText(CharSequence text),setTextColor(int color),setBackgroundResource(int resid)等相关方法
更多属性可以参考:
Android 复习笔记之图解View类的XML属性、相关方法及说明
1.使用onclick设置点击事件
在xml中写入如下代码,woyaodianzhege是我们调用的点击事件的函数,后续要在java文件中编写这个函数
<Button
android:id="@+id/Button_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="快点我"
android:textColor="@color/black"
android:onClick="woyaodianzhege" />
比如在java代码(.activity文件)中如下图设置一个弹出“你点到我了”的消息
public void woyaodianzhege(View v)
{
switch(v.getId()){
case R.id.Button_1:
Toast.makeText(Firstactivity.this,"你点到我了",Toast.LENGTH_SHORT).show();
break;
}
}
2.设置背景形状
layout中的xml代码
<Button
android:id="@+id/Button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="快点我"
android:layout_marginTop="10dp"
android:background="@drawable/shape_button_test1"
android:padding="10dp"
android:onClick="woyaodianzhege" />
shape_button_test1.xml中的代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--设置背景色-->
<solid android:color="@android:color/transparent"/>
<!--设置边框-->
<stroke android:width="5dp" android:color="@android:color/black"/>
<!--设置弧度-->
<corners android:radius="20dp"/>
</shape>
就会有如下的效果
有时候会失效可以尝试将res/values/themes.xml与夜间模式(应该是)下的res/values-night/themes.xml中的
<style name="Theme.HzhApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
改为
<style name="Theme.HzhApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar.Bridge">
参考:关于Android中Button的Backgroud背景设置默认为蓝紫色,且无法修改的问题
3.利用v7包中自带的Style样式设置按钮样式
<TextView
style="@style/Widget.AppCompat.Button.Colored"
android:id="@+id/Button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:onClick="woyaodianzhege"
android:padding="10dp"
android:text="快点我" />
这是V7包中自带的Style样式。按钮的颜色是ButtonTest/app/src/main/res/values/colors.xml下的name=“colorAccent”的颜色
可以参考Android总结之style(样式)和Theme(主题)
注意:1.Button中的setOnClickListener优先级比 xml中的android:onClick高,如果同时设置点击事件,只有setOnClickListener会生效
2.能用TextView就用TextView,Textview灵活性比Button高
三、EditText(文本编辑框)、
1.EditTextz支持的XML属性及相关方法
xml属性 | 相关方法 | 说明 |
---|---|---|
android:text | setText(CharSequence text) | 设置文本内容 |
android:textColor | setTextColor(int color) | 字体颜色 |
android:hint | setHint(int resid) | 内容为空时显示的文本 |
android:textColorHint | void setHintTextColor(int color) | 为空时显示的文本颜色 |
android:inputType | setInputType(int type) | 限制输入类型·number:整数类型·numberDecimal:小数点类型·date:日期类型·text:文本类型(默认值)·phone:拨号键盘·textPassword:密码·textVisiblePassword:可见密码·textUri:网址 |
android:maxLength | 限制显示的文本长度,超出部分不显示 | |
android:minLines | setMaxLines(int maxlines) | 设置文本的最小行数 |
android:gravity | setGravity(int gravity) | 设置文本位置,如设置成“center”,文本将居中显示 |
android:drawableLeft | setCompoundDrawables(Drawable left,Drawable top,Drawable right,Drawable bottom) | 在text的左边输出一个drawable,如图片 |
android:drawablePadding | 设置 text 与drawable(图片)的间隔,与drawableLeft、drawableRight、drawableTop、drawableBottom一起使用,可设置为负数,单独使用没有效果 | |
android:digits | 设置允许输入哪些字符,如“1234567890” | |
android:ellipsize | 设置当文字过长时该控件该如何显示·start:省略号显示在开头·end:省略号显示在结尾·middle:省略号显示在中间·marquee:以跑马灯的方式显示(动画横向移动) | |
android:lines | setLines(int lines) | 设置文本的行数,设置两行就显示两行,即使第二行没有数据 |
android:lineSpacingExtra | 设置行间距 | |
android:singleLine | setSingleLine() | true:单行显示false:可以多行 |
android:textStyle | 设置字形,可以设置一个或多个,用"\ |
2.制作输入密码框样例
效果
xml代码
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/mima"
android:background="@null"
android:inputType="textPassword"
android:maxLength="16"
android:hint="请输入密码"
android:drawableBottom="@drawable/xiahuaxian"
/>
制作下滑线的代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#1E7EE3"/>
<size android:height="1dp" android:width="500dp"/>
</shape>
3.EditText监听输入内容
顾名思义,监听输入内容的意思就是实时查看输入框内容的变化,并且做出相应的反应
比如我们使用百度时,输入框下方出现的我们可能想要搜索的内容
我们利用addTextChangedListener添加文本改变监听
用内部类方式实现TextWatcher接口
分别重写内容改变之前,内容改变时,和内容改变之后的调用
EditText xianshi=(EditText)findViewById(R.id.mima);
xianshi.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
}
});
详细参数和用法可以参考
Android TextWatcher三个回调详解,监听EditText的输入
四、单选&多选按钮
1.RadioButton(单选按钮)
单选按钮需要将RadioButton 和RadioGroup配合使用。
RadioGroup 是单选组合框(相当于容器),用于将RadioButton 框起来,在没有 RadioGroup的情况下,RadioButton可以全部选中;当多个RadioButton被RadioGroup包含的情况下,RadioButton
只可以选择一个。
xml代码
<RadioGroup
android:id="@+id/danxuan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<RadioButton
android:id="@+id/nan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="男" />
<RadioButton
android:id="@+id/nv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="女" />
</RadioGroup>
布局文件只能展示UI效果,但是我们的程序还要增加交互性,需要把用户选中的结果记录下来,所以还得在活动界面中监听RadioGroup的选择事件
RadioGroup danxuan=(RadioGroup)findViewById(R.id.danxuan);
danxuan.setOnCheckedChangeListener(Danxuan);
private RadioGroup.OnCheckedChangeListener Danxuan = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId){
if(checkedId==R.id.nan)
{Toast.makeText(Firstactivity.this,"您的性别是男",Toast.LENGTH_SHORT).show();}
else if(checkedId==R.id.nv)
{Toast.makeText(Firstactivity.this,"您的性别是女",Toast.LENGTH_SHORT).show();}
}
};
2.Checkbox(复选框)
xml代码
分别设置三个选项界面,和一个显示我选择了哪些选项的界面
<CheckBox
android:id="@+id/java"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="java" />
<CheckBox
android:id="@+id/c"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="c" />
<CheckBox
android:id="@+id/python"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="python" />
<TextView
android:id="@+id/Button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
活动代码中注意 要提前定义存文本id和字符串内容的变量
public class Firstactivity extends AppCompatActivity {
TextView textfuzhi;
private String js="",cs="",ps="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_layout);
textfuzhi=(TextView)findViewById(R.id.first_TextView);
CheckBox j=(CheckBox)findViewById(R.id.java);
CheckBox c=(CheckBox)findViewById(R.id.c);
CheckBox p=(CheckBox)findViewById(R.id.python);
j.setOnCheckedChangeListener(duoxuan);
c.setOnCheckedChangeListener(duoxuan);
p.setOnCheckedChangeListener(duoxuan);
}
private CompoundButton.OnCheckedChangeListener duoxuan =new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(buttonView.getId()==R.id.java)
//通过id区分不同复选框,buttonView.getId()可以同时等于多个值
js=isChecked?"java":"";
//如果选到了该选项就把“java”的值赋给js
if(buttonView.getId()==R.id.c)
cs=isChecked?"c":"";
if(buttonView.getId()==R.id.python)
ps=isChecked?"python":"";
textfuzhi.setText("您选择了"+js+" "+cs+" "+ps);
}
};
}
五、进度条
1.Progressbar(进度条)
这里使用了水平进度条和圆形进度条,水平进度条是确定进度的,而圆形进度条是无法确定进度的
这里多设置了两个按钮来控制水平进度条的进度
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<Button
android:id="@+id/Button_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="进度+"/>
<Button
android:id="@+id/Button_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="进度-"/>
<ProgressBar
android:id="@+id/pingtiao"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="100"
android:progress="40"/>
<ProgressBar
android:id="@+id/yuantiao"
style="@style/Widget.AppCompat.ProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
先制作两个按钮的监听器
findViewById(R.id.Button_2).setOnClickListener(jingdu);
findViewById(R.id.Button_3).setOnClickListener(jingdu);
再利用setProgress和getProgress方法改变进度条
private View.OnClickListener jingdu= new View.OnClickListener() {
@Override
public void onClick(View v) {
ProgressBar ping=findViewById(R.id.pingtiao);
switch(v.getId())
{
case R.id.Button_2:
ping.setProgress(ping.getProgress()+10);
break;
case R.id.Button_3:
ping.setProgress(ping.getProgress()-10);
break;
}
}
};
2.ProgressDialog(进度对话框)
首先创建一个按钮,然后再活动文件中修改如下代码
findViewById(R.id.Button_1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
jindukuang = ProgressDialog.show(Firstactivity.this,"标题","内容");
//创建新的进程,在新的进程里耗时
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
}catch (InterruptedException e){e.printStackTrace();}
jindukuang.dismiss();
}
}).start();
}
});
//创建对象,调用 Dialog 的 show方法显示
// ProgressDialog dialog = new ProgressDialog (this) ;
// dialog.setProgressStyle (ProgressDialog. STYLE_HORIZONTAL);//水平
// dialog.incrementProgressBy(20);//设置进度值
// dialog.setCanceledOnTouchOutside(false);
// 设置在点击Dialog 外是否取消Dialog进度条
// dialog.show(); 显示
// dialog.dismiss()关闭
// 调用ProgressDialog的静态方法显示5秒后关闭。模拟访问网络过程
按照如下可以设置水平进度条及其进度
jindukuang = new ProgressDialog(Firstactivity.this);
jindukuang.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
jindukuang.incrementProgressBy(20);
jindukuang.setCanceledOnTouchOutside(true);
jindukuang.show();
六、对话框
1.AlertDialog(简单对话框)
protected void showDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");//设置标题
builder.setMessage("确认退出吗?");//设置消息
builder.setIcon(R.mipmap.ic_launcher);//设置icon
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Firstactivity.this.finish();//结束当前Activity
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();//显示对话框
};
2.PopupWindow
PopupWindow弹出的窗口可以显示在屏幕任意位置,比Dialog对话框更加灵活
我们还可以通过setAnimationStyle方法设置PopupWindow的显示或隐藏动画
private void showAsDropDown(){
View popView= LayoutInflater.from(this).inflate(R.layout.pop,null);
//设置PopupWindow View宽度,高度
PopupWindow popupWindow=new PopupWindow(popView,LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//设置允许在点击外消失,必需要给popupWindow设置背景才会有效
popupWindow.setOutsideTouchable(true);
popupWindow.setBackgroundDrawable(new BitmapDrawable());
//显示在btnShowPopupwindow按钮下面,x位置偏移100px,就是偏移屏幕左边100px
//popupWindow.showAsDropDown(findViewById(R.id.Button_1),100,0);
//设置动画
popupWindow.setAnimationStyle(R.style.Animation_Design_BottomSheetDialog);
//参数1:根视图,整个Window界面的最顶层View 参数2:显示位置
popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.TOP,0,0);
}
popupWindow.setAnimationStyle(R.style.Animation_Design_BottomSheetDialog);
这段可以形成动画的原因参考:setAnimationStyle实现的popwindow显示消失的动画效果
本文章部分内容及代码参考自《Android App开发从入门到精通》