文章目录
参考书籍:第一行代码:Android(第二版)(郭霖):第三章
一、常用控件使用方法
6、ProgressBar
用于在界面上显示一个进度条,表明程序正在加载一些数据,运行之后会看到屏幕中有一个圆形的进度条正在旋转
<!--
android:visibility:控制是否可见visible(可见),invisible(不可见),gone(不可见且不占用地方)
style="@style/Widget.AppCompat.ProgressBar.Horizontal":设置水平进度条
android:max="100":进度条的最大值
android:progress:进度条已完成进度值
android:indeterminate:如果设置成true,则进度条不精确显示进度
style="?android:attr/progressBarStyleHorizontal"水平进度条
-->
<ProgressBar
android:id="@+id/progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"/>
<!--触动按钮时可以停止转动,部分Java代码-->
progressBar=(ProgressBar)findViewById(R.id.progress);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.button1:
String inputText=editText.getText().toString();
//消息提示
Toast.makeText(MainActivity.this,inputText,Toast.LENGTH_SHORT).show();
//通过按钮监控加载进度
// if(progressBar.getVisibility()==View.GONE){
// progressBar.setVisibility(View.VISIBLE);
// }else{
// progressBar.setVisibility(View.GONE);
// }
//动态修改水平进度条数据,每点击一次按钮进度条就加10
int projress=progressBar.getProgress();
projress=projress+10;
progressBar.setProgress(projress);
break;
default:
break;
}
}
});
7、AlertDialog
可以在当前的界面弹出一个对话框,这个对话框是置顶于所以界面元素之上的,能够屏蔽掉其他控件的交互能力,因此AlertDialog一般都是用于提示一些非常重要的内容或者警告信息,例如防止用户误删重要内容,在删除前弹出一个确认对话框
实现方式:
AlertDialog.Builder builder=new AlertDialog.Builder(context); | 构建Dialog的各种参数 |
---|---|
Builder.setIcon(int iconid); | 添加ICON |
Builder.setTitle(CharSequence title); | 添加标题 |
Builder.setMessage(CharSequence message); | 添加消息 |
Builder.setView(View view); | 设置自定义布局 |
Builder.create();创建Dialog | 创建Dialog |
Builder.show(); | 显示对话框 |
setPositiveButton | 确定按钮 |
setNegativeButton | 取消按钮 |
setNeutralButton | 中间按钮 |
代码演示一:
//onCreate()方法里面添加此代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*
首先通过AlertDialog.Builder创建一个AlertDialog的实例,然后可以为这个话题框设置标题、内容、
可否使用back键关闭对话框等属性,接下来调用setPositiveButton()方法为对话框设置确定按钮的点击事件
调用setNegativeButton()方法设置取消按钮的点击事件,最后调用show()方法将对话框显示出来
*/
switch(view.getId()){
case R.id.button1:
AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this);
dialog.setTitle("This is a dialog");
dialog.setMessage("Something important.");
//设置是否可以用back键返回
dialog.setCancelable(false);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
dialog.show();
break;
default:
break;
}
}
});
}
}
运行结果:
代码演示二:
布局文件一(主布局)activity_second.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/bu1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示对话框"
android:onClick="xyClick"/>
</LinearLayout>
布局文件二:
dialog_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ffff00">
<ImageView
android:src="@mipmap/ic_launcher"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="哈哈哈,天气很好"/>
</LinearLayout>
package com.example.test;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class SecondActivity extends AppCompatActivity {
private static final String TAG="SecondActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
public void xyClick(View view){
//添加自定义布局
View dialogview=getLayoutInflater().inflate(R.layout.dialog_view,null);
//1、构建各种参数
AlertDialog.Builder builder= new AlertDialog.Builder(this);
builder.setIcon(R.mipmap.ic_launcher)
.setTitle("这是对话框")//点击按钮显示的内容的标题
.setMessage("天气预报")//显示的内容
.setView(dialogview)//显示新的布局
//确定
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d(TAG, "onClick: 点击确定");
}
})
//取消
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d(TAG, "onClick: 点击取消");
}
})
//中间
.setNeutralButton("中间", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Log.d(TAG, "onClick: 点击中间");
}
})
.create()
.show();
}
}
运行结果:
8、ProgressDialog
和AlertDialog有点类似,都可以在界面上弹出一个对话框,都能够屏蔽掉其他控件的交互能力。不同的是,ProgressDialog会在对话框中显示一个进度条,一般用于标识当前操作比较耗时,让用户耐心等待。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* 通过点击按钮来获取EditText中输入的内容
* */
Button button=(Button) findViewById(R.id.button1);
editText=(EditText) findViewById(R.id.edit_text);
progressBar=(ProgressBar)findViewById(R.id.progress);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*
* 这里也是先构建一个ProgressDialog对象,然后同样可以设置标题,内容
* 可否取消等属性最后调用show()方法显示出来
* progressDialog.setCancelable(true)如果填了false则不能通过back键取消
* 就需要再数据加载出来之后使用dismiss()方法来关闭对话框,不然ProgressDialog会一直在
* */
switch(view.getId()){
case R.id.button1:
ProgressDialog progressDialog=new ProgressDialog(MainActivity.this);
progressDialog.setTitle("This is ProgressDialog");
progressDialog.setMessage("Loading......");
progressDialog.setCancelable(true);
progressDialog.show();
break;
default:
break;
}
}
});
}
运行结果:
9、Notification(通知)
创建一个NotificationManager类是一个通知管理器类,这个对象是由系统维护服务,是以单例模式的方式获得,所以一般并不直接实例化这个对象。在Activity中,可以使用Activity.getSystemService(String)方法获取。
NotificationManager对象,Activity.getSystemService(String)方法可以通过Android系统级服务的句柄,返回对应的对象。在这里需要返回NotificationManager,所以直接传递Context.NOTIFICATION_SERVICE即可。
使用Builder构造器来创建Notification对象,使用NotificationCompat类的Builder构造器来创建Notification对象,可以保证程序在所有版本上都能正常工作,Android8.0新增了通知渠道概念,如果没有设置,则通知无法在Android8.0的机器上显示。
NotificationChannel,通知渠道:Android8.0引入了通知渠道,其允许您为要显示的每种通知类型创建用户可自定义的渠道
通知重要程度设置,NofiticationManager类中
IMPORTANCE_NONE | 关闭通知 |
---|---|
IMPORTANCE_MIN | 开启通知,不会弹出,但没有提示音,状态栏中无显示 |
IMPORTANCE_LOW | 开启通知,不会弹出,不发出提示音,状态栏中显示 |
IMPORTANCE_DEFAULT | 开启通知,不会弹出,发出提示音,状态栏中显示 |
IMPORTANCE_HIGH | 开启通知,会弹出,发出提示音,状态栏中显示 |
Notification设置常见方法说明
setContentTitle(String string) | 设置标题 |
---|---|
setContentText(String string) | 设置文本内容 |
setSmallIcon(int icon) | 设置小图标 |
setLargeIcon(Bitmap icon) | 设置通知的大图标 |
setColor(int argb) | 设置小图标颜色 |
setContentIntent(PendingIntent intent) | 设置点击通知后的跳转意图 |
setAutoCancel(boolean boolean) | 设置点击通知后自动清除通知 |
setWhen(long when) | 设置通知被创建的时间 |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendNotification"
android:text="发出通知"/>
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="cacelNotification"
android:text="取消通知"/>
</LinearLayout>
MainActivity.java
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
public static final String TAG="MainActivity";
private NotificationManager manager;//1、通知管理类
private EditText editText;
private Notification notification;//2、通知
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);//3、返回对象
//4、判断安卓版本是否是8.0
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
//5、安卓8.0以上版本需要通知渠道,这里的id和下面的channelid要一致就行
NotificationChannel channel = new NotificationChannel("xxy","测试通知",NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
}
//6、点击通知信息然后活动跳转
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,intent,0);
notification=new NotificationCompat.Builder(this,"xxy")
.setContentTitle("官方通知") //通知标题
.setContentText("哈哈哈哈哈")//通知内容
.setSmallIcon(R.drawable.ic_baseline_favorite_24)//通知显示的小图标
.setContentIntent(pendingIntent)//通知跳转的页面
.setAutoCancel(true)//点击通知后自动清除通知
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ceshi))//通知附带的大图标
.build();//建立通知
}
public void sendNotification(View view){
manager.notify(1,notification);//发送通知
}
public void cacelNotification(View view){
manager.cancel(1);//取消通知
}
}
SecondActivity.java
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class SecondActivity extends AppCompatActivity {
private static final String TAG="SecondActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.d(TAG, "onCreate: 进入");
}
}
运行结果:
10、Toolbar
首先现将res/value/theme.xml修改
DarkActionBar改为NoActionBar
<style name="Theme.Test" parent="Theme.MaterialComponents.DayNight.NoActionBar">
替换每个页面的label标题
<androidx.appcompat.widget.Toolbar
android:background="#ffff00" 背景
app:navigationIcon="@drawable/ic_baseline_favorite_border_24" :导航图标
app:title="标题":主标题
app:titleTextColor="#ff0000" :主标题文字颜色
app:titleMarginStart="90dp":距离开始位置的距离(距离左边的位置)
app:subtitle="子标题":副标题
app:subtitleTextColor="#00ffff":副标题颜色
app:logo="@drawable/ic_baseline_favorite_24":图标
android:layout_width="match_parent":宽
android:layout_height="wrap_content"> :高
</androidx.appcompat.widget.Toolbar>
完整文件代码,也可以在JAVA代码中设置这些内容
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/tb"
android:background="#ffff00"
app:navigationIcon="@drawable/ic_baseline_favorite_border_24"
app:title="标题"
app:titleTextColor="#ff0000"
app:titleMarginStart="90dp"
app:subtitle="子标题"
app:subtitleTextColor="#00ffff"
app:logo="@drawable/ic_baseline_favorite_24"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
标题栏也可以嵌套其他控件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/tb"
android:background="#ffff00"
app:navigationIcon="@drawable/ic_baseline_favorite_border_24"
app:logo="@drawable/ic_baseline_favorite_24"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv"
android:text="标题"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</androidx.appcompat.widget.Toolbar>
</LinearLayout>
运行结果:
设置点击导航图标返回前一个活动:
//SecondActivity.java代码
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class SecondActivity extends AppCompatActivity {
private static final String TAG="SecondActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Log.d(TAG, "onCreate: 进入");
Toolbar toolbar=findViewById(R.id.tb);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onClick: toolbar被点击了");
Intent intent=new Intent(SecondActivity.this,MainActivity.class);
startActivity(intent);
}
});
};
}
11、PopupWindow(悬浮窗)
1、常用方法
setContentView(View contentView) | 设置PopupWindow显示的View |
---|---|
showAsDropDown(View anchor) | 相对某个控件的位置(正左下方),无偏移 |
showAsDropDown(View anchor, int xoff, int yoff) | 相对某个控件的位置,有偏移 |
setFocusable(boolean focusable) | 设置焦点(当点击空白处时消失) |
setBackgroundDrawable(Drawable background) | 设置背景 |
dismiss() | 关闭弹窗 |
setAnimationStyle(int) | 设置加载动画 |
setTouchable(boolean touchable) | 设置触摸使能 |
setOutsideTouchable(boolean touchable) | 设置PopupWindow外面的触摸使能 |
布局一:主布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:text="弹出PopupWindow"
android:onClick="xyClick2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
布局二:
pop_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/ic_launcher"
android:orientation="vertical">
<Button
android:id="@+id/btn1"
android:text="上学"
android:padding="5dp"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn2"
android:text="回家"
android:padding="5dp"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
public class ThirdActivity extends AppCompatActivity {
public static final String TAG="ThirdActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
}
public void xyClick2(View view) {
View pop_view=getLayoutInflater().inflate(R.layout.pop_view,null);
//参数1:点击是显示的布局 参数2参数3布局宽和高 参数4:设置焦点(当点击空白处时消失)
PopupWindow popupWindow=new PopupWindow(pop_view,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);
//设置背景
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.ceshi));
popupWindow.showAsDropDown(view);//正下方
//(view,100,100)
//(view,view.getWidth(),-view.getHeight())
//设置按钮触发
Button bnt1=pop_view.findViewById(R.id.btn1);
Button bnt2=pop_view.findViewById(R.id.btn2);
bnt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onLongClick: 按钮1");
//关闭弹窗
popupWindow.dismiss();
}
});
bnt2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "onLongClick: 按钮2");
//关闭弹窗
popupWindow.dismiss();
}
});
}
}
运行结果: