Day8SdCard存储

1.登录记住密码


public class MainActivity extends AppCompatActivity {

    private EditText username;
    private EditText password;
    private CheckBox cbRemember;
    private Button login;
    private SharedPreferences sp;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        sp = getSharedPreferences("login",MODE_PRIVATE);

        boolean isLogin = sp.getBoolean("isLogin", false);

        if (isLogin){
            String name = sp.getString("name", "");
            String pwd = sp.getString("pwd", "");
            username.setText(name);
            password.setText(pwd);
            cbRemember.setChecked(true);
        }
        this.login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cbRemember.isChecked()){

                    String name = username.getText().toString();
                    String pwd = password.getText().toString();

                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString("name",name);
                    edit.putString("pwd",pwd);
                    edit.putBoolean("isLogin",true);

                    edit.commit();
                }else {
                    SharedPreferences.Editor edit = sp.edit();
                    edit.clear();
                    edit.commit();
                }
            }
        });
    }

    private void initView() {

        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        cbRemember = (CheckBox) findViewById(R.id.cb_remember);
        login = (Button) findViewById(R.id.login);

    }

}

2.存入文件到SD卡

package com.example.day8;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Main5Activity extends AppCompatActivity {

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main5);
        requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},888);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 888&& grantResults[0]== PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this, "ok", Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this, "不ok", Toast.LENGTH_SHORT).show();
        }
    }

    public void writesd(View view) {
        String externalStorageState = Environment.getExternalStorageState();
        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)){
            File file = Environment.getExternalStorageDirectory();
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(new File(file, "abc.txt"));
                fileOutputStream.write("哈哈哈".getBytes());
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void readsd(View view) {
        String externalStorageState = Environment.getExternalStorageState();
        if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
            File file = Environment.getExternalStorageDirectory();
            try {
                FileInputStream fileInputStream = new FileInputStream(new File(file,"abc.txt"));
                StringBuilder stringBuilder = new StringBuilder();
                int len = 0;
                byte[] b = new byte[1024];
                while ((len = fileInputStream.read(b)) != -1) {
                    String s = new String(b, 0, len);
                    stringBuilder.append(s);
                }
                String s = stringBuilder.toString();
                Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

3.存数据到SD卡

public class Main2Activity extends AppCompatActivity {
    private Button btn;
    private Button btn2;
    private Button remove;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
       btn = (Button) findViewById(R.id.btn);
       btn2 = (Button) findViewById(R.id.btn2);
       remove = (Button) findViewById(R.id.remove);
    }

    public void btn(View view) {
        SharedPreferences one = getSharedPreferences("one", MODE_PRIVATE);
        SharedPreferences.Editor edit = one.edit();
        edit.putString("name", "小明");
        edit.putBoolean("isOpen", true);
        edit.putInt("age", 18);
        edit.putLong("bigAge", 999l);
        edit.putFloat("price", 9.9f);
        edit.commit();
    }

    public void btn2(View view) {
        SharedPreferences one = getSharedPreferences("one", MODE_PRIVATE);
        boolean isOpen = one.getBoolean("isOpen", false);
        String string = one.getString("name", "大明");
        int age = one.getInt("age", 16);
        long bigAge = one.getLong("bigAge", 998l);
        float price = one.getFloat("price", 9.8f);
        Toast.makeText(this, "" + isOpen + "-" + string + "-" + age + "-" + bigAge + "-" + price, Toast.LENGTH_SHORT).show();

    }

    public void remove(View view) {
        SharedPreferences one = getSharedPreferences("one", MODE_PRIVATE);
        SharedPreferences.Editor edit = one.edit();
        //edit.remove("age");
        edit.clear();
        edit.commit();
    }

}

4.TabLayout + ViewPager + 小圆点

布局页面

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab"
        app:tabSelectedTextColor="#E5AF35"
        app:tabTextColor="#969696"
        app:tabIndicatorColor="#B635E5"
        app:tabIndicatorHeight="5dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
    </com.google.android.material.tabs.TabLayout>
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="7">
    </androidx.viewpager.widget.ViewPager>
    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="30dp"
        android:layout_weight="1"
        android:gravity="center">
    </LinearLayout>
    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_weight="1"
        android:orientation="horizontal"
        android:layout_marginLeft="25dp"
        android:layout_gravity="center">
    <RadioButton
        android:id="@+id/btn1"
        android:onClick="btn1"
        android:textSize="25dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:button="@null"
        android:checked="true"
        android:textColor="@drawable/text_color_select"
        android:text="新闻"></RadioButton>
        <RadioButton
            android:id="@+id/btn2"
            android:onClick="btn2"
            android:textSize="25dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:textColor="@drawable/text_color_select"
            android:text="视频"></RadioButton>
        <RadioButton
            android:onClick="btn3"
            android:id="@+id/btn3"
            android:textSize="25dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:textColor="@drawable/text_color_select"
            android:text="图片"></RadioButton>
        <RadioButton
            android:id="@+id/btn4"
            android:onClick="btn4"
            android:textSize="25dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:button="@null"
            android:textColor="@drawable/text_color_select"
            android:text="留言"></RadioButton>
    </RadioGroup>

</LinearLayout>

Main 页面

package com.example.hwday09;

import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private TabLayout tab;
    private ViewPager vp;
    private Long time = 0l;
    private List<Fragment> list = new ArrayList<>();
    private List<String> titleList = new ArrayList<>();
    private LinearLayout ll;

    private OneFragment oneFragment = new OneFragment();
    private TwoFragment twoFragment = new TwoFragment();
    private ThreeFragment threeFragment = new ThreeFragment();
    private FourFragment fourFragment = new FourFragment();
    private RadioButton btn1;
    private RadioButton btn2;
    private RadioButton btn3;
    private RadioButton btn4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        list.add(new OneFragment());
        list.add(new TwoFragment());
        list.add(new ThreeFragment());
        list.add(new FourFragment());

        titleList.add("新闻");
        titleList.add("视频");
        titleList.add("图片");
        titleList.add("留言");

        final List<ImageView> imgList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ImageView imageView = new ImageView(this);
            if (i == 0) {
                imageView.setImageResource(R.drawable.circle_t);
            } else {
                imageView.setImageResource(R.drawable.circle_f);
            }
            imgList.add(imageView);
            ll.addView(imageView);
        }
        FgAdatepr fgAdatepr = new FgAdatepr(getSupportFragmentManager(), list, titleList);
        vp.setAdapter(fgAdatepr);
        tab.setupWithViewPager(vp);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < imgList.size(); i++) {
                    ImageView imageView = imgList.get(i);
                    if (i == position) {
                        imageView.setImageResource(R.drawable.circle_t);
                    } else {
                        imageView.setImageResource(R.drawable.circle_f);

                    }
                }
                //底部改变颜色
                
                switch (position) {
                    case 0:
                        btn1.setChecked(true);
                        break;
                    case 1:
                        btn2.setChecked(true);
                        break;
                    case 2:
                        btn3.setChecked(true);
                        break;
                    case 3:
                        btn4.setChecked(true);
                        break;
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        FragmentManager supportFragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = supportFragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.vp, oneFragment);
        fragmentTransaction.add(R.id.vp, twoFragment);
        fragmentTransaction.add(R.id.vp, threeFragment);
        fragmentTransaction.add(R.id.vp, fourFragment);
        fragmentTransaction.commit();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - time > 2000) {
                time = System.currentTimeMillis();
                return true;
            } else {
                finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initView() {
        tab = (TabLayout) findViewById(R.id.tab);
        vp = (ViewPager) findViewById(R.id.vp);
        ll = (LinearLayout) findViewById(R.id.ll);

        btn1 = (RadioButton) findViewById(R.id.btn1);
        btn2 = (RadioButton) findViewById(R.id.btn2);
        btn3 = (RadioButton) findViewById(R.id.btn3);
        btn4 = (RadioButton) findViewById(R.id.btn4);
    }
	//TODO:切换页面
    public void btn1(View view) {
        vp.setCurrentItem(0);

    }

    public void btn2(View view) {
        vp.setCurrentItem(1);
    }

    public void btn3(View view) {
        vp.setCurrentItem(2);
    }

    public void btn4(View view) {
        vp.setCurrentItem(3);
    }
}

5.下载设置图片

public class DownActivity extends AppCompatActivity {

    private Button down;
    private Button set;
    private ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down);


        down = (Button) findViewById(R.id.down);
        set = (Button) findViewById(R.id.set);
        img = (ImageView) findViewById(R.id.img);


        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},100);
        }

        set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//是否挂载
                    File file = Environment.getExternalStorageDirectory();
                    try {
                        final FileInputStream fileInputStream = new FileInputStream(new File(file, "daxia.jpg"));

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                img.setImageBitmap(BitmapFactory.decodeStream(fileInputStream));
                            }
                        });
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


        down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开启异步
                new MyTask().execute("http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg");
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            //yes
        }else{
            //no
            finish();
        }
    }

    class MyTask extends AsyncTask<String,Void, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... strings) {
            FileOutputStream out=null;
            InputStream inputStream=null;//网络连接的输入流
            HttpURLConnection connection=null;//向SD卡写的输出流
            try {
                URL url= new URL(strings[0]);
                connection= (HttpURLConnection) url.openConnection();
                //不要设置
//                connection.setConnectTimeout(5*1000);
//                connection.setReadTimeout(5*1000);
                if (connection.getResponseCode()==200){
                    inputStream = connection.getInputStream();

                    //下载
                    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//是否挂载
                        File file = Environment.getExternalStorageDirectory();
                        out = new FileOutputStream(new File(file,"daxia.jpg"));
                        byte[] bytes=new byte[1024];
                        int len=0;
                        while((len=inputStream.read(bytes))!=-1){
                            out.write(bytes,0,len);
                        }
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //关流
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(connection!=null){
                    connection.disconnect();
                }
            }
            return null;
        }

        //进度
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        //下载完,自动调用
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(DownActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值