繁体   English   中英

密码保护我的应用

[英]Password protecting my app

我对JAVA和android开发非常陌生,并尝试用密码保护我的应用程序。 我试图这样做,以便每当用户按下“提交”按钮时,如果密码正确,它将开始新的活动。

到目前为止,我有以下代码:

对于我的按钮:

 <Button
          android:id="@+id/button_enterpassword"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/text_enterpassword"
          android:layout_centerHorizontal="true"
          android:layout_marginTop="262dp"
          android:onClick="openMenu"
          android:textSize="60sp"
          android:text="@string/button_confirm"
           />

对于我的活动:

 // This is the method called when the user presses the button 
public void openMenu(View view) {
    MyMethods compareText = new MyMethods();
    boolean same = compareText.compareText();
    if(same = true){ 
    MyMethods openActivity = new MyMethods();
    openActivity.callActivity();
    }
}}

对于我的MyMethods类:

 public class MyMethods extends Activity {

public void callActivity() {

     Intent intent = new Intent(this , MainMenu.class);
        startActivity(intent);
}

public boolean compareText() {
    boolean same = false;
    //assigning the name sumbitButton to the button from the UI
    //Button sumbitButton = (Button) findViewById(R.id.button_enterpassword);
    //Defines when the user has selected the button
   // sumbitButton.setOnClickListener(new View.OnClickListener() {        
        //public void onClick(View v){
        //assigning the name passwordEditText to the text inside the textbox
        EditText passwordEditText = (EditText)         

  findViewById(R.id.text_enterpassword);
        if(passwordEditText.getText().toString().equals("Test")){
            same = true;

        }
        return same;
        }

}

但是,每当我按下按钮时,我的程序就会崩溃。

为您的帮助加油!

有两点需要注意:

  1. MyMethods正在扩展Activity,但是您使用它的方式是unorthodox
  2. 在openMenu()中,您的比较是错误的,您缺少一个= in

     if (same = true) { //<---------- should be if (same == true) or if (same) 
  3. 从MyMethods中删除callActivity()和compareText(),并在将要使用它们的类(即具有openMenu()的类)中声明它们。 我还要将compareText()重命名为isPasswordValid(),以使其更加清晰。

  4. 将openMenu()重写为:

     public void openMenu(View view) { if (isPasswordValid()) { callActivity(); } } 
  5. 您还可以重写compareText():

     public boolean isPasswordValid() { EditText passwordEditText = (EditText) findViewById(R.id.text_enterpassword); return passwordEditText.getText().toString().equals("Test"); } 
  6. 另外,由于您要启动另一个活动,因此请确保在AndroidManifest中声明了该活动。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM