1.SharedPerference和Edtor
public class MainActivity extends AppCompatActivity {
private Button read,write;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
read=findViewById(R.id.read);
write=findViewById(R.id.write);
//参数fengray是sharePerference的存储位置
sharedPreferences=getSharedPreferences("fengray",MODE_PRIVATE);
editor=sharedPreferences.edit();
write.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日"+"hh:mm:ss");
editor.putString("time",simpleDateFormat.format(new Date()));
editor.putInt("random",(int)(Math.random()*100));
editor.apply();
}
});
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String time=sharedPreferences.getString("time",null);
int randomNum=sharedPreferences.getInt("random",0);
String resulat=time==null?"您暂时还没有写入数据":"写入时间为:"+time+"\n 上次生成的随机数为:"+randomNum;
Toast.makeText(MainActivity.this,resulat,Toast.LENGTH_SHORT).show();
}
});
}
}
2.File存储
1、布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/txtRead"
android:hint="read"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<EditText
android:id="@+id/txtWrite"
android:hint="write"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btnRead"
android:text="read"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btnWrite"
android:text="write"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
2、activity文件
public class MainActivity extends AppCompatActivity {
public static final String FILENAME="fengray.txt";
private EditText txtRead,txtWrite;
private Button btnRead,btnWrite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtRead=findViewById(R.id.txtRead);
txtWrite=findViewById(R.id.txtWrite);
btnRead=findViewById(R.id.btnRead);
btnWrite=findViewById(R.id.btnWrite);
btnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//将read editor的内容写入文件
write(txtWrite.getText().toString());
txtWrite.setText("");
}
});
btnRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txtRead.setText(read());
}
});
}
private String read(){
try {
FileInputStream fileInputStream=openFileInput(FILENAME);
byte[] buff=new byte[1024];
int hasRead=0;
StringBuilder stringBuilder=new StringBuilder("");
//读取文件内容
while ((hasRead=fileInputStream.read(buff))>0){
stringBuilder.append(new String(buff,0,hasRead));
}
//关闭文件输入流
fileInputStream.close();
return stringBuilder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private void write(String content){
//以追加方式打开文件输出流,实际效果是覆盖了
FileOutputStream fileOutputStream= null;
try {
fileOutputStream = openFileOutput(FILENAME, Context.MODE_PRIVATE);
//将输出流包装成包装流printStream
PrintStream printStream=new PrintStream(fileOutputStream);
//输出文件内容
printStream.println(content);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
3.读写SD卡上的文件
1、布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edtWrite"
android:hint="input"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/txtRead"
android:hint="readsomthing"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btnRead"
android:text="Read"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btnWrite"
android:text="Write"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
2、manifest文件允许写入权限
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fengray.myex140sd">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
</manifest>
3、activity文件
public class MainActivity extends AppCompatActivity {
private static final String FILE_NAME="/fenngray.text";
private EditText edtWrite;
private TextView txtRead;
private Button btnRead,btnWrite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtWrite=findViewById(R.id.edtWrite);
txtRead=findViewById(R.id.txtRead);
btnRead=findViewById(R.id.btnRead);
btnWrite=findViewById(R.id.btnWrite);
btnWrite.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0x123);
}
});
btnRead.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},0x456);
}
});
}
public void write(String content){
//获取sd卡目录
File sdCardDir= Environment.getExternalStorageDirectory();
try {
File targetFile=new File(sdCardDir.getCanonicalPath()+FILE_NAME);
//以指定文件创建RandomAccessFile对象
RandomAccessFile randomAccessFile=new RandomAccessFile(targetFile,"rw");
//将文件记录指针移动到最后
randomAccessFile.seek(targetFile.length());
//输出文件内容
randomAccessFile.write(content.getBytes());
//关闭randomAcessFile
randomAccessFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String read(){
try {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//获取sd卡目录
File sdCardDir= Environment.getExternalStorageDirectory();
//获得指定文件的输入流
FileInputStream fileInputStream=new FileInputStream(sdCardDir.getCanonicalPath()+FILE_NAME);
//将指定输入流包装成缓冲流BufferReader
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(fileInputStream));
StringBuilder stringBuilder=new StringBuilder("");
String line=null;
//循环读取文件内容
while ((line=bufferedReader.readLine())!=null){
stringBuilder.append(line);
}
bufferedReader.close();
fileInputStream.close();
return stringBuilder.toString();
}
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode==0x123){//写操作
//如果用户同意授权访问
if (grantResults!=null && grantResults[0]== PackageManager.PERMISSION_GRANTED){
//写入内容
write(edtWrite.getText().toString());
edtWrite.setText("");
}
}else{
//提示用户sd写入权限
Toast.makeText(this, "没有获得写入权限", Toast.LENGTH_SHORT).show();
}
if (requestCode==0x456){//读操作
//如果用户同意授权访问
if (grantResults!=null && grantResults[0]== PackageManager.PERMISSION_GRANTED){
//读内容
txtRead.setText(read());
}else {
//提示用户sd写入权限
Toast.makeText(this, "没有获得写入权限", Toast.LENGTH_SHORT).show();
}
}
}
}
4.Gesture手势
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener {
GestureDetector gestureDEtector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDEtector=new GestureDetector(this,this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDEtector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent motionEvent) {
Toast.makeText(this, "this is ondown", Toast.LENGTH_SHORT).show();
return false;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
Toast.makeText(this,"this is on show press",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
Toast.makeText(this,"this is onsingletap up",Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
Toast.makeText(this,"this is onsiceoll",Toast.LENGTH_SHORT).show();
return false;
}
@Override
public void onLongPress(MotionEvent motionEvent) {
Toast.makeText(this,"this is onlongPress",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
Toast.makeText(this,"this is onfling",Toast.LENGTH_SHORT).show();
return false;
}
}
5.Gesture缩放图片
1.布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/myimg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>`
2,activity文件
public class MainActivity extends AppCompatActivity implements GestureDetector.OnGestureListener{
GestureDetector gestureDetector;
ImageView myimg;
Bitmap bitmap;
int width,height;
//记录当前的缩放比
float currentScal=1;
//控制图片缩放的Matrix对象
Matrix matrix;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDetector=new GestureDetector(this,this);
myimg=findViewById(R.id.myimg);
matrix=new Matrix();
//获取被缩放的原图片
bitmap= BitmapFactory.decodeResource(this.getResources(),R.drawable.di);
//获得位图的宽高
width=bitmap.getWidth();
height=bitmap.getHeight();
//初始化是显示的图片
myimg.setImageBitmap(BitmapFactory.decodeResource(this.getResources(),R.drawable.di));
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
@Override
public boolean onDown(MotionEvent motionEvent) {
return false;
}
@Override
public void onShowPress(MotionEvent motionEvent) {
}
@Override
public boolean onSingleTapUp(MotionEvent motionEvent) {
return false;
}
@Override
public boolean onScroll(MotionEvent motionEvent, MotionEvent motionEvent1, float v, float v1) {
return false;
}
@Override
public void onLongPress(MotionEvent motionEvent) {
}
@Override
public boolean onFling(MotionEvent motionEvent, MotionEvent motionEvent1, float velocityX, float velocityY) {
velocityX=velocityX>4000?4000:velocityX;
velocityX=velocityX<-4000?-4000:velocityX;
//根据手势的速度来计算ity缩放比,如果velocityx>0则放大图片,否则缩小
currentScal+=currentScal>0.01?currentScal:0.01f;
//重置Matrix
matrix.reset();
//缩放matrix
matrix.setScale(currentScal,currentScal,160,200);
BitmapDrawable temp=(BitmapDrawable)myimg.getDrawable();
//如果图片未收回,先强制收回该图片
if (!temp.getBitmap().isRecycled()){
temp.getBitmap().recycle();
}
//根据原始位图和matrix创建新图片
Bitmap bitmap2=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
myimg.setImageBitmap(bitmap2);
return true;
}
}
6.多点触碰缩放文本
1、自定义myTouchView类继承自TextView
@SuppressLint("AppCompatCustomView")
public class TouchZoonView extends TextView {
private float textSize;
//保存两个手指前一次的距离
private float preDist;
public TouchZoonView(Context context) {
super(context);
}
public TouchZoonView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public TouchZoonView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//只处理触碰点大于或等于2的情形
if (event.getPointerCount()>2){
//获得该TextView默认的字号大小
if (textSize==0){
textSize=this.getTextSize();
}
//对于多点触碰,使用getActionMasked来获取触摸事件类型
switch (event.getActionMasked()){
case MotionEvent.ACTION_POINTER_DOWN:
//计算两个个手指之间的距离
preDist=calSpace(event);
break;
//处理手指移动的事件
case MotionEvent.ACTION_MOVE:
//实时计算两个个手指之间的距离
float curVDist=calSpace(event);
//根据两个手指之间的距离计算缩放比
zoom(curVDist/preDist);
//为下一次移动的缩放做准备
preDist=curVDist;
break;
}
}
return true;
}
private float calSpace(MotionEvent event){
//获取两个点之间x坐标和y坐标的差值并计算距离
float x=event.getX(0)-event.getX(1);
float y=event.getY(0)-event.getY(1);
return (float)Math.sqrt(x*x+y*y);
}
private void zoom(float f){
textSize *=f;
this.setTextSize(px2sp(getContext(),textSize));
}
private static int px2sp(Context context, float pxValue) {
float fontScale=context.getResources().getDisplayMetrics().scaledDensity;
return (int)(pxValue/fontScale+0.5f);
}
}
2、activity文件
将自定义view添加到布局文件中
public class MainActivity extends AppCompatActivity {
private LinearLayout myll;
private TouchZoonView myTouch;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myll=findViewById(R.id.myll);
myTouch=new TouchZoonView(this);
myTouch.setBackgroundColor(Color.BLUE);
myTouch.setText("hello world!hello world!"+"\n"+" hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello " +
"world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!");
myll.addView(myTouch);
}
}