【问题标题】:How do I make a variable global across a Java file如何在 Java 文件中创建全局变量
【发布时间】:2016-03-26 16:39:34
【问题描述】:

在 lua 中,我可以做 global variablename 并 bam 它的全局 在java中有没有简单的方法来做到这一点?

这是我的代码,我希望 loc 变量是全局变量,以便 public View getView(int position, View convertView, ViewGroup parent){ 可以使用它:

class custom_row_adapter extends ArrayAdapter<Integer> {
      custom_row_adapter(Context context, int picId, String url) {
        super(context, R.layout.activity_custom_row_adapter, picId);
        String loc = url;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
        LayoutInflater picInflater = LayoutInflater.from(getContext());
        View customView = picInflater.inflate(R.layout.activity_custom_row_adapter, parent, false);
        String singlePic = getItem(loc + String.valueOf(position) + ".jpg"); **//this is where loc is viewed**
        ImageView theImage = (ImageView) customView.findViewById(R.id.singleImg);
        Glide.with(this).load(singlePic).into(theImage);
        return customView;
}

}

【问题讨论】:

  • 在这种情况下,我相信您需要将其设为 public static String loc,但您需要将其放在 class custom_row ..... 行之后,并且要访问它,您需要执行 custom_row_adapter.loc
  • 就语言而言,java 中没有全局变量作用域(没有变量的全局命名空间)。但是您可以通过完全限定引用来引用任何公共静态成员(例如 MyClass.myStaticPublicField)
  • @3kings 成功了!将其发布为答案?

标签: java variables global-variables


【解决方案1】:

只需像这样添加它和字段

public class example {

private String loc;

class custom_row_adapter extends ArrayAdapter<Integer> {
    custom_row_adapter(Context context, int picId, String url) {
        super(context, R.layout.activity_custom_row_adapter, picId);
        loc = url;
    }
  }
}

【讨论】:

    猜你喜欢
    • 2017-11-12
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多