简体   繁体   English

如何获取方法的返回值?

[英]How to get the return value of a method?

I'm a newbie creating a unit converter.我是创建单位转换器的新手。 I have two classes, I have this method in the first class:我有两个类,我在第一类中有这个方法:

public String cardName;

public String StartConversion(View view){
    Intent intent = new Intent(this, ConversionActivity.class);
    startActivity(intent);
    return cardName = view.getResources().getResourceEntryName(view.getId());
}

I would like to get and use the cardName's value in my second class, so:我想在我的第二堂课中获取并使用 cardName 的值,所以:

MainActivity myObj = new MainActivity();
Toast.makeText(getApplicationContext(), "cardName: " + myObj.cardName, Toast.LENGTH_LONG).show();

But this doesn't work.但这不起作用。 I know local variables are only accessible inside their scope so I did this instead.我知道局部变量只能在它们的范围内访问,所以我这样做了。 They say you can only access it if you make it a class member, that does work but then it has a NULL value.他们说只有将其设为类成员才能访问它,这确实有效,但它具有 NULL 值。

Typically, you'd a) create some class, b) make class members "private", then c) expose those members with getter and setter methods .通常,您会 a) 创建一些类,b) 将类成员设为“私有”,然后 c) 使用getter 和 setter 方法公开这些成员。

EXAMPLE:例子:

public class MyClass {

  private String cardName;

  public void StartConversion(View view){
    Intent intent = new Intent(this, ConversionActivity.class);
    startActivity(intent);
    cardName = view.getResources().getResourceEntryName(view.getId());
  }

  public getCardName() { return cardName; }
}

Then whatever class wanted to access "cardName" would call:然后任何想要访问“cardName”的类都会调用:

String cardName = myObject.getCardName();

Look here for more details: Java Getter and Setter Tutorial, Nam Ha Minh在此处查看更多详细信息: Java Getter 和 Setter 教程,Nam Ha Minh

There exists a train of way to resolve your problem.有一系列方法可以解决您的问题。 For instance,例如,

First- the method of StartConversion works to set the card name and then provide a method of getter to access.首先- StartConversion 的方法用于设置卡片名称,然后提供一个 getter 方法来访问。

Second- Only use the method of StartConversion to return that you want.第二 - 只使用 StartConversion 的方法来返回你想要的。 But you ought to change the code to return view.getResources().getResourceEntryName(view.getId());但是您应该更改代码以return view.getResources().getResourceEntryName(view.getId()); , to remove the cardName = . , 删除cardName = The outer class should be called the method to access that you want.外部类应该被称为您想要访问的方法。

In a word, either call the method to access directly or giving a setter then using the getter to access.一句话,要么调用方法直接访问,要么给个setter再用getter访问。

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

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