无法从onClickListener调用方法

时间:2014-07-29 09:59:42

标签: java android

我是Android的新手,只是试图理解它,但我似乎无法让它工作:我想当用户点击按钮时,将调用一个方法来查看如果输入的2密码包含相同的文本,如果他们这样做,将弹出AlertDialog框,说明密码已设置。然而,感谢你的帮助,警告对话盒根本不会弹出一些原因。

package com.example.jhonti.test2;

import android.app.Activity;
import android.app.AlertDialog;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MyActivity extends Activity {

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


    // It works when I put it here
    //AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
    //altDialog.setMessage("Password set"); // here add your message
    //altDialog.show();


    final EditText a = (EditText) findViewById(R.id.editText);
    final EditText c = (EditText) findViewById(R.id.editText2);

    Button b = (Button) findViewById(R.id.button1);
    b.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {

            if(a.getText().toString() == c.getText().toString())
            {
                setPass(a.getText().toString(), c.getText().toString());
            }
        }
    });
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.my, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

private void setPass(String i, String o)
{
    if((i == o) && (i != ""))
    {
        AlertDialog.Builder altDialog = new AlertDialog.Builder(this);
        altDialog.setMessage("Password set"); // here add your message
        altDialog.show();

    }
}

}

3 个答案:

答案 0 :(得分:2)

尝试使用此.equals()方法进行String比较

 if(a.getText().toString().equals(c.getText().toString()))

答案 1 :(得分:0)

在代码中

而不是

a.getText().toString() == c.getText().toString()

使用

a.getText().toString().equals(c.getText().toString())

你无法按照你的方式比较两个字符串

答案 2 :(得分:-1)

你应该删除final。而是不使用任何东西或公共