无法解析符号视图。 public void onClick(查看视图)不起作用?

问题描述 投票:0回答:3

我似乎有onClick(View视图)的问题

Here's the screenshot of my android studio.

我已经导入了android.view.View。这是我的代码

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
    totalTextView = (TextView) findViewById(R.id.totalTextView);
    percentageTxt = (EditText) findViewById(R.id.percentageTxt);
    numberTxt = (EditText) findViewById(R.id.numberTxt);


    Button calcBtn = (Button) findViewById(R.id.calcBtn);
    calcBtn.setOnClickListener(new View.onClickListener()){
          @Override
          public void onClick(View view){
            float percentage = Float.parseFloat(percentageTxt.getText().toString());
            float dec = percentage / 100;
            float total = dec * Float.parseFloat(numberTxt.getText().toString());
            totalTextView.setText(Float.toString(total));
        }
    }

}
android android-studio onclick
3个回答
0
投票

那是因为你有一个额外的右括号,语法不正确:

calcButton.setOnClickListener(new View.OnClickListener()) { // extra closing bracket ')'

并将其更改为:

calcButton.setOnClickListener(new View.OnClickListener() {

0
投票

你必须修改这句话:

Button calcBtn = (Button) findViewById(R.id.calcBtn);
    calcBtn.setOnClickListener(new View.onClickListener())/* -->this parenthesis should not be closed here*/ { 
          @Override
          public void onClick(View view){
            float percentage = Float.parseFloat(percentageTxt.getText().toString());
            float dec = percentage / 100;
            float total = dec * Float.parseFloat(numberTxt.getText().toString());
            totalTextView.setText(Float.toString(total));
        }
    }

应该:

Button calcBtn = (Button) findViewById(R.id.calcBtn);
        calcBtn.setOnClickListener(new View.onClickListener() { 
              @Override
              public void onClick(View view){
                float percentage = Float.parseFloat(percentageTxt.getText().toString());
                float dec = percentage / 100;
                float total = dec * Float.parseFloat(numberTxt.getText().toString());
                totalTextView.setText(Float.toString(total));
            }
        });

0
投票

你的匿名函数声明有一个拼写错误。此外,还有一个额外的右括号。

calcBtn.setOnClickListener(new View.onClickListener())

应该

calcBtn.setOnClickListener(new View.OnClickListener()

修复声明和右括号后,让我们知道它是否仍然没有找到View参数。

© www.soinside.com 2019 - 2024. All rights reserved.