【问题标题】:The method getString(int) is undefined for the type Apps类型 Apps 的方法 getString(int) 未定义
【发布时间】:2012-10-21 16:35:49
【问题描述】:

如何解决此错误。底部的所有三个字符串都会出现以下错误“方法 getString(int) 未定义类型 Apps”。请帮忙,我是个菜鸟。

package com.actionbarsherlock.sample.fragments;

import android.content.Context;
import android.content.res.Resources;


public final class Apps {
/**
 * Our data, part 1.
 */
public static final String[] TITLES =
{
        "title1",
        "title2",
        "title3"
};

/**
 * Our data, part 2.
 */
public static final String[] DIALOGUE = { 

    getString(R.string.text1),

    getString(R.string.string2),

    getString(R.string.string3)

};
}

【问题讨论】:

  • 你试图调用一个不存在的方法。在不知道您要做什么的情况下,我们确实无法帮助您解决问题。
  • 你的意思是扩展一些东西吗?你想继承什么?
  • 帮我解决这个问题的人说“getString来自activity类,所以你的类需要从activity继承,或者你需要从已经从activity继承的类中调用getString。”跨度>
  • 我想要做的是调用它们保存文本值的三个字符串

标签: java android eclipse android-activity getstring


【解决方案1】:

传递Context context的实例

然后使用

context.getResources().getString(R.string.text1)

这里context 属于您当前的活动。

【讨论】:

  • 我遵循了这个并将 Preferences.getBoolean(getString(R.string.pref_mypreference), false) 重写为 Preferences.getBoolean(***getContext().***getString(R.string.pref_mypreference ), false) 并且 Bob 成了我的叔叔 :D (*** 不是字面意思,只是显示了变化);)
【解决方案2】:

第一个getString 不是静态方法,您是在静态上下文中调用它,这是无法做到的。

第二个getString方法是Resources类的一部分,你的类没有扩展Resources类所以找不到方法。

我认为使用其构造函数将Resources 类的实例解析为Apps 类将是您的最佳选择。

类似这样的:

public final class Apps {

    public Apps(Resources r){
     DIALOGUE = new String[]{
        r.getString(R.string.text1),
        r.getString(R.string.string2),
        r.getString(R.string.string3)};
    }


/**
 * Our data, part 1.
 */
public static final String[] TITLES =
{
        "title1",
        "title2",
        "title3"
};

/**
 * Our data, part 2.
 */
public static String[] DIALOGUE;
}

【讨论】:

  • 摆脱了错误,但我必须修复一些其他问题,我会用结果报告 :)
  • mhhh 当我选择一个类别然后应用程序标题应用程序强制关闭。我会玩更多,但你的回答是最有帮助的。
【解决方案3】:

创建Application的子类,例如public class App extends Application { 在 AndroidManifest.xml 中设置标签的 android:name 属性以指向您的新类,例如android:name=".App" 在您的应用实例的 onCreate() 方法中,将您的上下文(例如 this)保存到名为 mContext 的静态字段并创建一个返回此字段的静态方法,例如获取上下文():

它应该是这样的:

public class App extends Application{

    private static Context mContext;

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
    }

    public static Context getContext(){
        return mContext;
    }
}

现在你可以使用:App.getContext().getString()

【讨论】:

    【解决方案4】:

    你可以试试

    getResources().getString(R.string.somestrid);
    

    getApplicationContext().getResources().getString(R.string.somestrid);
    

    【讨论】:

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