2021-06-09Android控件

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

本文针对常用控件(Textview、Button、EditText、RadioButton、CheckBox、ImageView)进行简单说明。

和布局类似,控件至少需要设置的属性为android:layout_widthandroid:layout_height,分别控制布局的宽度和高度,一般填入的参数为match_parent和wrap_content,也可填入具体尺寸 。
android:id也必不可少,id属性只能接受资源类型的值,也就是必须以@开头的值,在R中用一个int类型的值来表示。比如@+id/xyz,在R.java中表示为int xyz = value,其中value是一个十六进制数。

@id和@+id的区别:
@+id,就是在R.java文件里新增一个id名称,如果之前已经存在相同的id名称,那么会覆盖之前的名称。
@id,则是直接引用R.java文件的存在的id资源,如果不存在,会编译报错。


一、TextView

1.常见属性

常见属性
布局文件中常用的几个单位

  • dp(dip): device independent pixels(设备独立像素)不同设备有不同的显示效果
  • px: pixels(像素): 不同设备显示效果相同
  • sp: scaled pixels(放大像素): 主要用于字体显示
  • pt:(point):是一个标准的长度单位,1pt=1/72英寸,不常用

2.文本框阴影

android:shadowColor:阴影的颜色
android:shadowDx:水平方向上的偏移量
android:shadowDy:垂直方向上的偏移量
android:shadowRadius:是阴影的的半径大少

    <TextView
        android:id="@+id/tv_shadow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="60sp"
        android:textColor="@color/colorRed"
        android:layout_gravity="center"
        android:text="Shadow"
        --关键属性
        android:shadowColor="#ff000000"
        android:shadowRadius="1"
        android:shadowDx="30"
        android:shadowDy="30"/>

在这里插入图片描述

3.跑马灯效果

android:singleLine=“true” //单行显示
android:ellipsize=“marquee” //文字循环滚动
android:marqueeRepeatLimit=“marquee_forever” //设定为永久循环
android:focusable=“true” //获取键盘焦点
android:focusableInTouchMode=“true” //获取触屏焦点

方法1:设置TextView可以点击,并设置获取触屏焦点的属性为true

    <TextView
        android:id="@+id/tv_shadow"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="60sp"
        android:textColor="@color/colorRed"
        android:layout_gravity="center"
        android:text="Shadow  Shadow  Shadow  Shadow  Shadow  Shadow"
        android:textStyle="italic"
        android:shadowColor="#ff000000"
        android:shadowRadius="1"
        android:shadowDx="30"
        android:shadowDy="30"
        --关键属性
        android:singleLine="true" 
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true" --获取触屏焦点
        android:clickable="true"/>  --设置可以点击
        

方法2:自定义TextView

package com.example.apptest;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.annotation.Nullable;

public class MyTextView extends TextView {

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean isFocused() {
        return true;
    }
}
    <com.example.apptest.MyTextView
        ...
        android:singleLine="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true"/>

或者

 <TextView
        ...
        android:singleLine="true" 
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:focusable="true"
        android:focusableInTouchMode="true" 
        android:clickable="true">
        <requestFocus/> --去MyTextView.java请求焦点
        </TextView>  

二、Button

1.基本按钮

如下:

        <Button
            android:id="@+id/Btn1"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_marginTop="5dp"
            android:text="按钮1"/>

2.点击出现变化

        <Button
            android:id="@+id/Btn1"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_marginTop="5dp"
            android:text="按钮1"/>

3.Button事件处理

点击事件

        //点击事件
        Btn_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG,"onClick");
            }
        });

长按事件

		//长按事件
        Btn_tv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
            	Log.e(TAG,"onLongClick");
                return false;
                //return true;//此时长按点击不会调用上面的onClick方法
            }
        });

触摸事件

        //触摸事件
        Btn_tv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
            	Log.e(TAG,"onTouch"+event.getAction());
                return false;
                //return true;//此时长按点击也不会调用上面两个方法
            }
        });

点击时移动然后松手,执行顺序:
点击移动时 onTouch0–onLongClick–onTouch2
松手时 onTouch1–onClick

方法2
在XML里定义点击事件

        <Button
            .....
            android:onClick="testBTN"/>

在这里插入图片描述

       //长按事件
        Btn_tv.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Log.e(TAG,"onLongClick");
                return false;
            }
        });

        //触摸事件
        Btn_tv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                Log.e(TAG,"onTouch"+event.getAction());
                return false;
            }
        });
    }

	//代替了原来的Btn_tv.setOnClickListener
    public void testBTN(View view) {
        Log.e(TAG,"onClick");
    }

三、EditText

常用属性
android:hint 输入时输入框的提示文本
android:inputType 指定输入类型,如果指定为phone类型,手机键盘会自动弹出数字键盘,同时输入也只接受数字类型。
android:maxLines=“1” 指定输入框的最大行数为1,防止格式变形

在这里插入图片描述

四、ImageView

1.基本属性

文本属性
文本内容属性:android:text=""
文本颜色属性:android:textColor=""
文本字体大小属性:android:textSize="" ,一般单位 sp 。

图片属性
android:scaleType=""
对应属性值
android:scaleType=“fitXY” 表示X、Y轴拉伸铺满,撑满控件,宽高比可能变化
android:scaleType=“fitCenter” 完全显示,保持宽高比缩放,可能无法铺满,背景可能会显示
android:scaleType=“centerCrop” 完全覆盖控件,保持宽高比缩放,一定铺满,图片可能显示不全

效果:

    <!--    android:scaleType="fitXY" X、Y轴拉伸铺满,撑满控件,宽高比可能变化-->
    <ImageView
        android:id="@+id/IV1"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_margin="15dp"
        android:scaleType="fitXY"
        android:src="@drawable/wangyiyun" />
        
    <!--    android:scaleType="fitCenter" 完全显示,保持宽高比缩放,可能无法铺满,背景可能会显示-->
    <ImageView
        android:id="@+id/IV2"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_margin="15dp"
        android:scaleType="fitCenter"
        android:src="@drawable/wangyiyun"  />

    <!--    android:scaleType="centerCrop" 完全覆盖控件,保持宽高比缩放,一定铺满,图片可能显示不全-->
    <ImageView
        android:id="@+id/IV3"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_margin="15dp"
        android:scaleType="centerCrop"
        android:src="@drawable/wangyiyun"  />

效果与代码对应:
在这里插入图片描述

2.获取网络图片

java 调用 glide 库

在这里插入代码片

五、ProgressBar(进度条)

常用属性
在这里插入图片描述
在JAVA中可以调用以下方法

getMax():返回这个进度条的范围的上限
getProgress():返回进度
getSecondaryProgress():返回次要进度
incrementProgressBy(int diff):指定增加的进度
isIndeterminate():指示进度条是否在不确定模式下
setIndeterminate(boolean indeterminate):设置不确定模式下

默认的一些进度条样式

    <!-- 系统提供的圆形进度条,依次是大中小 -->
    <ProgressBar
        style="@android:style/Widget.ProgressBar.Small"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ProgressBar
        style="@android:style/Widget.ProgressBar.Large"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <!--系统提供的水平进度条-->
    <ProgressBar
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="100"
        android:progress="18" />

    <ProgressBar
        style="@android:style/Widget.ProgressBar.Horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:indeterminate="true" />

点击按钮,隐藏进度条

    <ProgressBar
        android:id="@+id/pb1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:indeterminate="true" />
    <Button
        android:id="@+id/btn"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginTop="5dp"
        android:onClick="leoClick"
        android:text="ImageView"/>
public class MainActivity extends AppCompatActivity {
    private ProgressBar progressBar,progressBar2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        progressBar = findViewById(R.id.pb1);
        progressBar2 = findViewById(R.id.pb2);
    }



    public void leoClick(View view) {
        if(progressBar.getVisibility() == View.GONE){
            progressBar.setVisibility(View.VISIBLE);
        } else {
            progressBar.setVisibility(View.GONE);
        }
    }

}

点击按钮,进度条增加10%

    public void load(View view) {
      int progress =  progressBar2.getProgress();
        progress += 10;
        progressBar2.setProgress(progress);
    }

六、Notification

通知栏消息显示

状态通知栏主要涉及到2个类:Notification 和NotificationManager
Notification:通知信息类,它里面对应了通知栏的各个属性
NotificationManager:是状态栏通知的管理类,负责发通知、清除通知等操作。
使用的基本流程:
Step 1. 获得NotificationManager对象: NotificationManager mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Step 2. 创建一个通知栏的Builder构造类: Notification.Builder mBuilder = new Notification.Builder(this);
Step 3. 对Builder进行相关的设置,比如标题,内容,图标,动作等!
Step 4.调用Builder的build()方法为notification赋值
Step 5.调用NotificationManager的notify()方法发送通知!
PS:另外我们还可以调用NotificationManager的cancel()方法取消通知

    <Button
        android:id="@+id/btn1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginTop="5dp"
        android:onClick="sendNC"
        android:text="发出通知"/>

    <Button
        android:id="@+id/btn2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_marginTop="5dp"
        android:onClick="cancelNC"
        android:text="取消通知"/>
public class MainActivity<manager> extends AppCompatActivity {
    private  NotificationManager manager;
    private Notification notification;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 创造一个NotificationManager
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        
        // 创建NotificationChannel,是创建Notification的channelid必需的
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            NotificationChannel channel = new NotificationChannel("leo","测试通知",NotificationManager.IMPORTANCE_HIGH);
            
            //创建channel之后放到NotificationManager里,配置的id要和下面创建notification的channelid一致
            manager.createNotificationChannel(channel);
        }
        
        //使用Bulider构造器来创建Notification对象
        notification = new NotificationCompat.Builder(this,"leo")
                .setContentTitle("测试通知栏") //设置标题,必需
                .setContentText("这里是内容,必需") //内容,必需
                .setSmallIcon(R.drawable.checked) //通知图标不能有颜色,必需
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.wangyiyun))//设置大图标,不必需
                .setColor(Color.parseColor("#FF0000"))//小图标颜色
                //.setContentIntent()
                .build();   
    }


    //触发条件:点击按钮,发送通知
    public void sendNC(View view) {
        manager.notify(1,notification);
    }

    //触发条件,点击按钮,取消通知
    public void cancelNC(View view) {
    }
}

七、AlterDialog

对话框

创建AlertDialog的步骤:
1、创建AlertDialog.Builder对象
2、调用Builder对象的setTitle方法设置标题,setIcon方法设置图标
3、调用Builder相关方法如setMessage方法、setItems方法、setSingleChoiceItems方法、setMultiChoiceItems方法、setAdapter方法、setView方法设置不同类型的对话框内容。
4、调用setPositiveButton、setNegativeButton、setNeutralButton设置多个按钮
5、调用Builder对象的create()方法创建AlertDialog对象
6、调用AlertDialog对象的show()方法将对话框显示出来

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_dialog_one;
    private Button btn_dialog_two;
    private Button btn_dialog_three;
    private Button btn_dialog_four;

    private Context mContext;
    private boolean[] checkItems;

    private AlertDialog alert = null;
    private AlertDialog.Builder builder = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        bindView();


    }

    private void bindView() {
        btn_dialog_one = (Button) findViewById(R.id.btn_dialog_one);
        btn_dialog_two = (Button) findViewById(R.id.btn_dialog_two);
        btn_dialog_three = (Button) findViewById(R.id.btn_dialog_three);
        btn_dialog_four = (Button) findViewById(R.id.btn_dialog_four);
        btn_dialog_one.setOnClickListener(this);
        btn_dialog_two.setOnClickListener(this);
        btn_dialog_three.setOnClickListener(this);
        btn_dialog_four.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //普通对话框
            case R.id.btn_dialog_one:
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setTitle("系统提示:")
                        .setMessage("这是一个最普通的AlertDialog,\n带有三个按钮,分别是取消,中立和确定")
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "你点击了取消按钮~", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "你点击了确定按钮~", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNeutralButton("中立", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(mContext, "你点击了中立按钮~", Toast.LENGTH_SHORT).show();
                            }
                        }).create();             //创建AlertDialog对象
                alert.show();                    //显示对话框
                break;
            //普通列表对话框
            case R.id.btn_dialog_two:
                final String[] lesson = new String[]{"语文", "数学", "英语", "化学", "生物", "物理", "体育"};
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setTitle("选择你喜欢的课程")
                        .setItems(lesson, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(), "你选择了" + lesson[which], Toast.LENGTH_SHORT).show();
                            }
                        }).create();
                alert.show();
                break;
            //单选列表对话框
            case R.id.btn_dialog_three:
                final String[] fruits = new String[]{"苹果", "雪梨", "香蕉", "葡萄", "西瓜"};
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setTitle("选择你喜欢的水果,只能选一个哦~")
                        .setSingleChoiceItems(fruits, 0, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(getApplicationContext(), "你选择了" + fruits[which], Toast.LENGTH_SHORT).show();
                            }
                        }).create();
                alert.show();
                break;
            //多选列表对话框
            case R.id.btn_dialog_four:
                final String[] menu = new String[]{"水煮豆腐", "萝卜牛腩", "酱油鸡", "胡椒猪肚鸡"};
                //定义一个用来记录个列表项状态的boolean数组
                checkItems = new boolean[]{false, false, false, false};
                alert = null;
                builder = new AlertDialog.Builder(mContext);
                alert = builder.setIcon(R.mipmap.ic_icon_fish)
                        .setMultiChoiceItems(menu, checkItems, new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                checkItems[which] = isChecked;
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String result = "";
                                for (int i = 0; i < checkItems.length; i++) {
                                    if (checkItems[i])
                                        result += menu[i] + " ";
                                }
                                Toast.makeText(getApplicationContext(), "客官你点了:" + result, Toast.LENGTH_SHORT).show();
                            }
                        })
                        .create();
                alert.show();
                break;
        }
    }
}

八、PopupWindow

当点击btn时,在底部弹出PopupWindow,然后点击各个item弹出对应toast

实际 开发中用得较多的几个构造方法:
public PopupWindow (Context context)
public PopupWindow(View contentView, int width, int height)
public PopupWindow(View contentView)
public PopupWindow(View contentView, int width, int height, boolean focusable)

public class MainActivity extends AppCompatActivity {

    private Button btn_show;
    private Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = MainActivity.this;
        btn_show = (Button) findViewById(R.id.btn_show);
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initPopWindow(v);
            }
        });
    }


    private void initPopWindow(View v) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_popup, null, false);
        Button btn_xixi = (Button) view.findViewById(R.id.btn_xixi);
        Button btn_hehe = (Button) view.findViewById(R.id.btn_hehe);
        //1.构造一个PopupWindow,参数依次是加载的View,宽高
        final PopupWindow popWindow = new PopupWindow(view,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        popWindow.setAnimationStyle(R.anim.anim_pop);  //设置加载动画

        //这些为了点击非PopupWindow区域,PopupWindow会消失的,如果没有下面的
        //代码的话,你会发现,当你把PopupWindow显示出来了,无论你按多少次后退键
        //PopupWindow并不会关闭,而且退不出程序,加上下述代码可以解决这个问题
        popWindow.setTouchable(true);
        popWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话,touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效


        //设置popupWindow显示的位置,参数依次是参照View,x轴的偏移量,y轴的偏移量
        popWindow.showAsDropDown(v, 50, 0);

        //设置popupWindow里的按钮的事件
        btn_xixi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "你点击了嘻嘻~", Toast.LENGTH_SHORT).show();
            }
        });
        btn_hehe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "你点击了呵呵~", Toast.LENGTH_SHORT).show();
                popWindow.dismiss();
            }
        });
    }
}

总结

提示:这里对文章进行总结:
例如:以上就是今天要讲的内容

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值