【问题标题】:Calling a void method in java在java中调用一个void方法
【发布时间】:2018-05-10 14:19:11
【问题描述】:

我是 Java 新手,在没有任何运气的情况下四处寻找答案。我正在尝试调用另一个方法,但没有任何运气。

我在受保护的 onCreate 中有这个

    final RelativeLayout rlayout = (RelativeLayout) findViewById(R.id.mainlayout);
    rlayout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mLevelTextView = (TextView) findViewById(R.id.level);
            mLevelTextView.setText(Integer.toString(clickCounter));

            yellowLevelText = (TextView) findViewById(R.id.yellowLevel);
            yellowLevelText.setText(Integer.toString((clickCounter - 1) / 256 + 1));
            //this is what I am trying to call but get an error
            savedInfo();

            rlayout.setBackgroundColor(Color.parseColor("#" + decToHex(colorNumber)));
            colorNumber = new Integer(colorNumber - 1);
            clickCounter = new Integer(clickCounter + 1);
        }

    });

这是我试图调用的代码末尾的方法:

    public void saveInfo(View view) {
    SharedPreferences sharedPref = getSharedPreferences("score", 
    Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("totalScore", clickCounter);
    editor.putInt("yellowScore", yellowCounter);
    editor.putInt("magentaScore", magentaCounter);
    editor.putInt("cyanScore", cyanCounter);
    editor.apply();
}

我得到的错误是: 错误:类启动中的方法 saveInfo 不能应用于给定类型; 必需:查看 发现:没有参数 原因:实际参数列表和形式参数列表的长度不同

任何有更多经验的人都能看出这里可能出了什么问题?

【问题讨论】:

  • 您正在尝试呼叫saveInfo()。您需要致电saveInfo(someView)
  • savedInfo() 接受一个参数。除此之外,您没有在方法中使用参数,因此只需将其删除。使其简单为 ` public void saveInfo() `

标签: java android methods call


【解决方案1】:

您正在尝试拨打saveInfo()。您需要致电saveInfo(someView)

虽然实际上,您的 saveInfo 方法对该参数没有任何作用,因此只需将其删除。方法签名应该是:

public void saveInfo() {

【讨论】:

  • @rmlan 是的。也许这只是一个错字。编译器错误明确指出 saveInfo 调用不正确。
  • 哦,我真傻。我没有读那么远,也没有看到 OP 实际上发布了编译器错误。
【解决方案2】:

你执行方法saveInfo 没有任何参数。您必须传递 View 类型的参数

【讨论】:

  • 这应该是一条评论
【解决方案3】:

将点击视图传递给方法.. v

 @Override
    public void onClick(View v) {
        mLevelTextView = (TextView) findViewById(R.id.level);
        mLevelTextView.setText(Integer.toString(clickCounter));

        yellowLevelText = (TextView) findViewById(R.id.yellowLevel);
        yellowLevelText.setText(Integer.toString((clickCounter - 1) / 256 + 1));
        //this is what I am trying to call but get an error
        savedInfo(v);

        rlayout.setBackgroundColor(Color.parseColor("#" + decToHex(colorNumber)));
        colorNumber = new Integer(colorNumber - 1);
        clickCounter = new Integer(clickCounter + 1);
    }

});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多