Android自学笔记(一)

intent消息互传

activity_act_request:

    <TextView
        android:id="@+id/tv_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btn_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="传送请求数据"/>

    <TextView
        android:id="@+id/tv_response"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

activity_act_request:(类似)

ActRequestActivity.java:

public class ActRequestActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_request;
    private String mRequest = "你睡了吗?来我家睡";
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;
    private TextView tv_response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_request);
        tv_request = findViewById(R.id.tv_request);
        tv_request.setText("待发送的消息为" + mRequest);

        tv_response = findViewById(R.id.tv_response);

        findViewById(R.id.btn_request).setOnClickListener(this);

        //startActivityForResult已过时,采用回调的方式代替
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result != null) {
                Intent intent = result.getData();
                if (intent != null && result.getResultCode() == Activity.RESULT_OK) {
                    Bundle bundle = intent.getExtras();
                    String response_time = bundle.getString("response_time");
                    String response_content = bundle.getString("response_content");
                    String desc = String.format("收到返回信息:\n应答时间为%s\n应答内容为%s", response_time, response_content);
                    tv_response.setText(desc);
                    tv_response.setBackgroundResource(R.color.purple_200);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, ActResponseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("request_time", DateUtil.getNowTime());
        bundle.putString("request_content", mRequest);
        intent.putExtras(bundle);
        intentActivityResultLauncher.launch(intent);//不能忘记
    }
}

ActResponseActivity.java:

public class ActResponseActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tv_request;
    public static final String mResponse = "我还没睡,我爸妈不在家";
    private TextView tv_response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_act_response);
        tv_request = findViewById(R.id.tv_request);
        Bundle bundle = getIntent().getExtras();
        String request_time = bundle.getString("request_time");
        String request_content = bundle.getString("request_content");
        String desc = String.format("收到请求信息:\n请求时间为%s\n请求内容为%s", request_time, request_content);
        tv_request.setText(desc);
        findViewById(R.id.btn_response).setOnClickListener(this);
        tv_response = findViewById(R.id.tv_response);
        tv_response.setText("待返回的消息为:" + mResponse);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("response_time", DateUtil.getNowTime());
        bundle.putString("response_content", mResponse);
        intent.putExtras(bundle);
        setResult(Activity.RESULT_OK, intent);
        finish();
    }
}

跳转到不同界面:

        String phoneNo = "12345";
        Intent intent;
        switch (v.getId()){
            case R.id.btn_tel:
                intent = new Intent();
                intent.setAction(Intent.ACTION_DIAL);
                //"tel:"是固定的
                Uri uri = Uri.parse("tel:" + phoneNo);
                intent.setData(uri);
                startActivity(intent);
                break;
            case R.id.btn_mes:
                intent = new Intent();
                intent.setAction(Intent.ACTION_SENDTO);
                Uri uri2 = Uri.parse("smsto:"+phoneNo);
                intent.setData(uri2);
                startActivity(intent);
                break;
            case R.id.btn_my:
                intent = new Intent();
                //跳转的自定义界面要在清单文件中设置相应的action和category
                intent.setAction("android.intent.action.NING");
                intent.addCategory("android.intent.category.DEFAULT");
                startActivity(intent);
                break;
        }

其中,第三种会跳转到设置对应属性的界面,注意exported要为true,表示可以被其他应用跳转。(测试发现如果在同一Project下,有多个满足上面第三种跳转条件的Activity,系统会弹出选择弹窗,可以选择始终跳转或仅一次跳转到此页面)

这里有个问题:如果设置action的name为android.intent.action.MY(自己写的),可以匹配到当前Module下对应的Activity,但是匹配不到当前Project下的其他Module中的Activity,使用android.intent.action.NING就都能匹配。

利用资源文件配置字符串:

好处:不需要编译成其他格式(java需要编译成class),更加灵活

<string name="weather_str">晴天</string>
String value = getString(R.string.weather_str);
tv_resource.setText(value);

利用元数据传递配置信息:

场景:用到第三方SDK的Activity,要验证在网上注册的Token值是否匹配

清单文件:activity标签内

<meta-data android:name="weather" android:value="晴天"/>
        PackageManager pm = getPackageManager();//获取包管理器
        try {
            ActivityInfo info = pm.getActivityInfo(getComponentName(), PackageManager.GET_META_DATA);//获取当前Activity的信息对象
            Bundle bundle = info.metaData;
            String weather = bundle.getString("weather");
            tv_meta.setText(weather);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

给应用页面注册快捷方式:

 创建三个页面:FirstActivity、SecondActivity、ThirdActivity

清单文件:(其他两个页面的exported设置为true)

        <activity
            android:name=".FirstActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.app.shortcuts"
                android:resource="@xml/shortcuts" />
        </activity>

在res文件夹下新建xml文件夹->shortcuts.xml:注意这里的label标签都要写在strings.xml文件中

<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">
    <shortcut
        android:shortcutId="first"
        android:enabled="true"
        android:icon="@mipmap/ic_launcher"
        android:shortcutShortLabel="first"
        android:shortcutLongLabel="启停活动">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example.activitytest"
            android:targetClass="com.example.activitytest.FirstActivity" />
        <categories android:name="android.shortcut.conversation"/>
    </shortcut>

    <shortcut
        android:shortcutId="second"
        android:enabled="true"
        android:icon="@mipmap/ic_launcher"
        android:shortcutShortLabel="second"
        android:shortcutLongLabel="来回跳转">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example.activitytest"
            android:targetClass="com.example.activitytest.SecondActivity" />
        <categories android:name="android.shortcut.conversation"/>
    </shortcut>

    <shortcut
        android:shortcutId="third"
        android:enabled="true"
        android:icon="@mipmap/ic_launcher"
        android:shortcutShortLabel="third"
        android:shortcutLongLabel="登录返回">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example.activitytest"
            android:targetClass="com.example.activitytest.ThirdActivity" />
        <categories android:name="android.shortcut.conversation"/>
    </shortcut>
</shortcuts>

焦点变更监听:(当手机号码输入不满11位切换焦点到密码时,手机号码的edittext获取到焦点)

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_focus);
        et_telephone = findViewById(R.id.et_telephone);
        et_password = findViewById(R.id.et_password);
        btn_login = findViewById(R.id.btn_login);
        et_password.setOnFocusChangeListener(this);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(hasFocus){
            String phone = et_telephone.getText().toString();
            if(TextUtils.isEmpty(phone) || phone.length() < 11){
                et_telephone.requestFocus();
                Toast.makeText(this,"请输入11位手机号码",Toast.LENGTH_LONG).show();
            }
        }
    }

文本变化监听器:(当editText输入满一定位数时,自动退出键盘)

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_hide);
        et_phone = findViewById(R.id.et_telephone);
        et_password = findViewById(R.id.et_password);

        et_phone.addTextChangedListener(new HideTextWatcher(et_phone,11));
        et_password.addTextChangedListener(new HideTextWatcher(et_password,6));
    }

    private class HideTextWatcher implements TextWatcher {
        private EditText mView;
        private int mMaxLength;
        public HideTextWatcher(EditText v, int maxLength) {
            this.mView = v;
            this.mMaxLength = maxLength;
        }

        @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) {//Editable是EditText对象getText()的返回值
            String str = s.toString();
            if (str.length() == mMaxLength){
                ViewUtil.hideOneInputMethod(EditHideActivity.this,mView);
            }
        }

xml:

    <EditText
        android:id="@+id/et_telephone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入11位电话号码"
        android:background="@drawable/edittest_selector"
        android:maxLength="11"
        android:inputType="number"/>

    <EditText
        android:id="@+id/et_password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入6位时自动隐藏输入法"
        android:background="@drawable/edittest_selector"
        android:maxLength="6"
        android:inputType="textPassword"/>

ViewUtil实现退出键盘:

public static void hideOneInputMethod(Activity act, View v){
        InputMethodManager imm = (InputMethodManager) act.getSystemService(Context.INPUT_METHOD_SERVICE);
        //getWindowToken()相当于拿到这个窗口的令牌。
        // Android操作系统中有很多窗口,每个窗口都要在AMS(Activity Manager Service)中注册,窗口的关闭隐藏都要把令牌传给AMS找到对应窗口进行操作)
        imm.hideSoftInputFromWindow(v.getWindowToken(),0);
    }

AlertDialog的使用:(使用了建造者模式builder)

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("尊敬的用户");
    builder.setMessage("你真的要卸载我吗?");
    builder.setPositiveButton("我再想想", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            tv_alert.setText("留下来");
        }
    });
    builder.setNegativeButton("残忍卸载", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            tv_alert.setText("卸载了");
        }
    });
    AlertDialog dialog = builder.create();
    dialog.show();

 DatePickerDialog和DatePicker:

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_ok:
                String desc = String.format("您选择的日期是%d年%d月%d日",dp_date.getYear(),dp_date.getMonth() + 1,dp_date.getDayOfMonth());
                tv_date.setText(desc);
                break;
            case R.id.btn_choose:
                Calendar calendar = Calendar.getInstance();
                int year = calendar.get(Calendar.YEAR);
                int month = calendar.get(Calendar.MONTH);
                int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
                DatePickerDialog dialog = new DatePickerDialog(this,this,year,month,dayOfMonth);//默认值
                dialog.show();
                break;
        }
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        //月份范围是0-11
        String desc = String.format("您选择的日期是%d年%d月%d日",year,month + 1,dayOfMonth);
        tv_date.setText(desc);
    }
<Button
        android:id="@+id/btn_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="选择日期"/>

<!--默认显示当前日期-->
<!--spinner是上下滑动选择器,calendar是像日历一样的选择器-->
    <DatePicker
        android:id="@+id/dp_"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:datePickerMode="spinner" 
        android:calendarViewShown="false"/>

    <Button
        android:id="@+id/btn_ok"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="确定"/>

    <TextView
        android:id="@+id/tv_date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

 TimePicker和TimePickerDialog:(同上类似)

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_choose:
                Calendar calendar = Calendar.getInstance();
                TimePickerDialog dialog = new TimePickerDialog(this,this,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MINUTE),true);
                dialog.show();
                break;
            case R.id.btn_ok:
                String str = String.format("您选择的时间是:%d:%d",tp_time.getHour(),tp_time.getMinute());
                tv_time.setText(str);
                break;
        }
    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        String str = String.format("您选择的时间是:%d:%d",hourOfDay,minute);
        tv_time.setText(str);
    }
    <Button
        android:id="@+id/btn_choose"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="请选择时间"/>

    <TimePicker
        android:id="@+id/tp_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:timePickerMode="spinner"/>

    <Button
        android:id="@+id/btn_ok"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="确定"/>

    <TextView
        android:id="@+id/tv_time"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

登录的例子:

strings.xml:(&#160;为空格)

    <string name="login_by_password">密码登录</string>
    <string name="login_by_vertifycode">验证码登录</string>
    <string name="phone_number">手机号码:</string>
    <string name="inout_phone_number">请输入手机号码</string>
    <string name="login_password">登录密码:</string>
    <string name="input_password">请输入密码</string>
    <string name="forget_password">忘记密码</string>
    <string name="remember_password">记住密码</string>
    <string name="login">登&#160;&#160;录</string>
    <string name="inout_new_password">输入新密码:</string>
    <string name="inout_new_password_hint">请输入新密码</string>
    <string name="confirm_new_password">确认新密码:</string>
    <string name="confirm_new_password_again">请再次确认新密码</string>
    <string name="verifycode">&#160;&#160;&#160;&#160;验证码:</string>
    <string name="inpout_verifycode">请输入验证码</string>
    <string name="get_verifycode">获取验证码</string>
    <string name="done">确&#160;&#160;认</string>

dimens.xml:

<resources>
    <dimen name="common_font_size">17sp</dimen>
    <dimen name="button_font_size">20sp</dimen>
    <dimen name="item_layout_height">50dp</dimen>
</resources>

LoginMainActivity.java:

public class LoginMainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener, View.OnClickListener {

    private RadioGroup rg_login;
    private TextView tv_password;
    private EditText et_password;
    private Button btn_forget;
    private CheckBox ck_remember;
    private EditText et_phone;
    private RadioButton rb_verifycode;
    private RadioButton rb_password;
    private ActivityResultLauncher<Intent> register;
    private Button btn_login;
    private String mPassword="111111";
    private String mVerifyCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_main);
        rg_login = findViewById(R.id.rg_login);
        rg_login.setOnCheckedChangeListener(this);
        tv_password = findViewById(R.id.tv_password);
        et_password = findViewById(R.id.et_password);
        et_phone = findViewById(R.id.et_phone);
        btn_forget = findViewById(R.id.btn_forget);
        btn_forget.setOnClickListener(this);
        ck_remember = findViewById(R.id.ck_remember);
        et_password.addTextChangedListener(new HideTextWatcher(et_password,6));
        et_phone.addTextChangedListener(new HideTextWatcher(et_phone,11));
        rb_password = findViewById(R.id.rb_password);
        rb_verifycode = findViewById(R.id.rb_verifycode);
        register = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                Intent intent = result.getData();
                if(intent != null && result.getResultCode() == Activity.RESULT_OK){
                    mPassword = intent.getStringExtra("new_password");
                }
            }
        });
        btn_login = findViewById(R.id.btn_login);
        btn_login.setOnClickListener(this);
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.rb_password:
                tv_password.setText(getString(R.string.login_password));
                et_password.setHint(getString(R.string.input_password));
                btn_forget.setText(getString(R.string.forget_password));
                ck_remember.setVisibility(View.VISIBLE);
                break;
            case R.id.rb_verifycode:
                tv_password.setText(getString(R.string.verifycode));
                et_password.setHint(getString(R.string.inpout_verifycode));
                btn_forget.setText(getString(R.string.get_verifycode));
                ck_remember.setVisibility(View.GONE);
                break;
        }
    }

    @SuppressLint({"DefaultLocale", "NonConstantResourceId"})
    @Override
    public void onClick(View v) {
        String phone = et_phone.getText().toString();
        if(phone.length()<11){
            Toast.makeText(this,"请输入正确的手机号",Toast.LENGTH_LONG).show();
            return;
        }
        switch(v.getId()){
            case R.id.btn_forget:
                //选择了密码方式校验,此时要跳到找回密码页面
                if (rb_password.isChecked()){
                    Intent intent = new Intent(this,LoginForgetActivity.class);
                    intent.putExtra("phone",phone);
                    register.launch(intent);
                }else if(rb_verifycode.isChecked()){
                    //生成六位数,范围是0-999999,如果生成位数不满6位,用0代替
                    mVerifyCode = String.format("%06d",new Random().nextInt(999999));
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("请记住验证码");
                    builder.setMessage("手机号"+phone+",本次验证码是"+mVerifyCode+",请输入验证码");
                    builder.setPositiveButton("好的",null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
                break;
            case R.id.btn_login:
                if(rb_password.isChecked()){
                    if (!mPassword.equals(et_password.getText().toString())){
                        Toast.makeText(this,"请输入正确的密码",Toast.LENGTH_LONG).show();
                        return;
                    }
                    //提示用户登录成功
                    loginSuccess();
                }else if (rb_verifycode.isChecked()){
                    if(!mVerifyCode.equals(et_password.getText().toString())){
                        Toast.makeText(this,"请输入正确的密码",Toast.LENGTH_LONG).show();
                        return;
                    }
                }
                //提示用户登录成功
                loginSuccess();
                break;
        }
    }

    private void loginSuccess() {
        String desc = String.format("您的手机号码是%s,恭喜你通过登录验证,点击\"确定\"按钮返回上一个页面",et_phone.getText().toString());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("登录成功");
        builder.setMessage(desc);
        builder.setPositiveButton("确定返回", (dialog, which) -> finish());
        builder.setNegativeButton("我再看看",null);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    //定义一个编辑框监听器,在输入文本达到指定长度时自动隐藏输入法
    private class HideTextWatcher implements TextWatcher {
        private int mMaxLength;
        private EditText mView;

        public HideTextWatcher(EditText v, int maxLength) {
            this.mMaxLength = maxLength;
            this.mView = v;
        }

        @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) {
            String str = s.toString();
            if(str.length() == mMaxLength){
                ViewUtil.hideOneInputMethod(LoginMainActivity.this,mView);
            }
        }
    }
}

 activity_login_main.xml:

<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=".exe10.LoginMainActivity">

    <RadioGroup
        android:id="@+id/rg_login"
        android:layout_width="match_parent"
        android:layout_height="@dimen/item_layout_height"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/rb_password"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/login_by_password"
            android:textSize="@dimen/common_font_size"
            android:checked="true"/>

        <RadioButton
            android:id="@+id/rb_verifycode"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/login_by_vertifycode"
            android:textSize="@dimen/common_font_size"/>

    </RadioGroup>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/item_layout_height"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/phone_number"
            android:gravity="center"
            android:textSize="@dimen/common_font_size"
            android:textColor="@color/black"/>

        <EditText
            android:id="@+id/et_phone"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:background="@drawable/edittest_selector"
            android:hint="@string/inout_phone_number"
            android:inputType="number"
            android:maxLength="11"
            android:textColor="@color/black"
            android:textColorHint="@color/grey"
            android:textSize="17sp"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/item_layout_height"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_password"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/login_password"
            android:gravity="center"
            android:textSize="@dimen/common_font_size"
            android:textColor="@color/black"/>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <EditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"
                android:background="@drawable/edittest_selector"
                android:hint="@string/input_password"
                android:maxLength="11"
                android:textColor="@color/black"
                android:textColorHint="@color/grey"
                android:textFontWeight="1"
                android:textSize="@dimen/common_font_size" />

            <Button
                android:id="@+id/btn_forget"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="@string/forget_password"
                android:layout_alignParentRight="true"
                android:textSize="@dimen/common_font_size"
                android:textColor="@color/black"/>

        </RelativeLayout>

    </LinearLayout>

    <CheckBox
        android:id="@+id/ck_remember"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/remember_password"
        android:textColor="@color/black"
        android:textSize="@dimen/common_font_size" />

    <Button
        android:id="@+id/btn_login"
        android:text="@string/login"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="@dimen/button_font_size"
        android:textColor="@color/black"/>

</LinearLayout>

LoginForgetActivity.java:

public class LoginForgetActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_password;
    private EditText et_second_password;
    private EditText et_verify;
    private Button btn_verify;
    private Button btn_done;
    private String mPhone;
    private String mVerifyCode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_forget);
        et_password = findViewById(R.id.et_password);
        et_second_password = findViewById(R.id.et_second_password);
        et_verify = findViewById(R.id.et_verifycode);
        btn_verify = findViewById(R.id.btn_get_verify);
        btn_done = findViewById(R.id.btn_done);
        mPhone = getIntent().getStringExtra("phone");
        btn_verify.setOnClickListener(this);
        btn_done.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_get_verify:
                mVerifyCode = String.format("%06d",new Random().nextInt(999999));
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("请记住验证码");
                builder.setMessage("手机号"+mPhone+",本次验证码是"+mVerifyCode+",请输入验证码");
                builder.setPositiveButton("好的",null);
                AlertDialog dialog = builder.create();
                dialog.show();
                break;
            case R.id.btn_done:
                String password_first = et_password.getText().toString();
                String password_second = et_second_password.getText().toString();
                if(password_first.length()<6){
                    Toast.makeText(this,"请输入正确的密码",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!password_first.equals(password_second)){
                    Toast.makeText(this,"两次输入的新密码不一致",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!mVerifyCode.equals(et_verify.getText().toString())){
                    Toast.makeText(this,"请输入正确的验证码",Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(this,"密码修改成功",Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.putExtra("new_password",password_first);
                setResult(Activity.RESULT_OK,intent);
                finish();
                break;
        }
    }
}

activity_login_forget.xml:

<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=".exe10.LoginForgetActivity"
    android:padding="5dp">

     <LinearLayout
         android:orientation="horizontal"
         android:layout_width="match_parent"
         android:layout_height="50dp">

         <TextView
             android:layout_width="wrap_content"
             android:layout_height="match_parent"
             android:text="@string/inout_new_password"
             android:textColor="@color/black"
             android:gravity="center"
             android:textSize="@dimen/common_font_size"/>

         <EditText
             android:id="@+id/et_password"
             android:layout_marginTop="5dp"
             android:layout_marginBottom="5dp"
             android:layout_width="0dp"
             android:layout_height="match_parent"
             android:layout_weight="1"
             android:hint="@string/inout_new_password_hint"
             android:background="@drawable/edittest_selector"
             android:textColorHint="@color/grey"
             android:textSize="@dimen/common_font_size"
             android:inputType="numberPassword"
             android:maxLength="6"/>

     </LinearLayout>

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="50dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="@string/confirm_new_password"
            android:gravity="center"
            android:textColor="@color/black"
            android:textSize="@dimen/common_font_size"/>

        <EditText
            android:id="@+id/et_second_password"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="5dp"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:hint="@string/confirm_new_password_again"
            android:background="@drawable/edittest_selector"
            android:textColorHint="@color/grey"
            android:textSize="@dimen/common_font_size"
            android:inputType="numberPassword"
            android:maxLength="6"/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="        验证码:"
            android:textSize="@dimen/common_font_size"
            android:gravity="center"
            android:textColor="@color/black"/>

        <RelativeLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1">

            <EditText
                android:id="@+id/et_verifycode"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"
                android:background="@drawable/edittest_selector"
                android:hint="@string/inpout_verifycode"
                android:inputType="numberPassword"
                android:maxLength="6"
                android:textColorHint="@color/grey"
                android:textSize="@dimen/common_font_size" />

            <Button
                android:id="@+id/btn_get_verify"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:text="@string/get_verifycode"
                android:textColor="@color/black"
                android:textSize="@dimen/common_font_size" />


        </RelativeLayout>

    </LinearLayout>

    <Button
        android:id="@+id/btn_done"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:text="@string/done"
        android:textSize="@dimen/button_font_size"
        android:textColor="@color/black"/>

</LinearLayout>

注意:

1.EditTest第一次点击获取focus,第二次点击触发点击事件

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
作为AI语言模型,我只能提供一些Android开发的基础知识和常用概念,希望对您有所帮助。 1. Android组成部分 Android操作系统由四个主要组成部分组成:应用程序、应用程序框架、系统运行库和硬件抽象层。 2. Activity Activity是Android应用程序中的一个组件,用于表示应用程序中的一个屏幕。Activity可以包含用户界面元素,如文本框、按钮和图像。 3. Intent Intent是Android应用程序中的一个基本组件,用于在不同的组件之间传递数据。Intent可以用于启动Activity、启动服务、发送广播等。 4. 布局 布局是Android应用程序中用于定义用户界面的XML文件。布局文件定义了应用程序中的视图层次结构,包括文本框、按钮、图像等。 5. AndroidManifest.xml AndroidManifest.xml是Android应用程序中的一个必需文件,用于描述应用程序的基本信息。该文件包含应用程序的包名、应用程序的入口Activity、应用程序需要的权限等信息。 6. 生命周期 Android应用程序中的每个组件都有自己的生命周期,包括创建、启动、暂停和销毁。了解组件的生命周期可以帮助开发者更好地管理应用程序的资源。 7. 线程 Android应用程序中的线程用于执行长时间运行的操作,如下载文件或执行计算。但是,在主线程中执行长时间运行的操作会导致应用程序变得缓慢或停止响应,因此必须使用异步线程。 8. Service Service是Android应用程序中的一种组件,用于在后台执行长时间运行的操作。与Activity不同,Service没有用户界面,可以在后台执行。 9. 广播 广播是Android应用程序中的一种机制,用于在不同组件之间传递消息。广播可以用于通知应用程序中的其他组件,例如当设备电池电量低时,应用程序可以发送广播通知其他组件。 10. 内存管理 内存管理是Android应用程序中的一个重要方面。Android应用程序必须管理内存以确保应用程序能够正常运行,并避免出现内存泄漏和内存溢出等问题。可以使用垃圾回收器、使用合适的数据结构、避免创建不必要的对象等方法来管理内存。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值