簡體   English   中英

getResources()引發錯誤

[英]getResources() is throwing an error

我有以下代碼,用於在帶有兩個標簽的應用程序中創建自定義ListView

package com.test.testing;

import android.content.Context;
import android.text.Html;

public class SetRows {
    int image;
    String name;
    String id;

    public int getImage () {
        return image;
    }

    public void setImage (int image) {
        this.image = image;
    }

    public String getName () {
        return name;
    }

    public void setName (String name) {
        this.name = name;
    }

    public String getID () {
        return id;
    }

    public void setID (String id) {
        this.id = id;
    }

    public SetRows(int image, String name, String id) {

        super();
        this.image = image;
        this.name = Html.fromHtml(getResources().getString(R.string.colorcol)) + " COLOR: \n\t" + name;
        this.id = "MEANS: \n\t" +  id;
    }

}

下一行:

this.name = Html.fromHtml(getResources().getString(R.string.colorcol)) + " COLOR: \\n\\t" + name;

給我以下錯誤:

The method getResources() is undefined for the type SetRows

您需要更改代碼,以便您可以引用當前上下文,從而可以訪問getResources

例如

public SetRows(Context currentContext,int image, String name, String id) {

        super();

        this.image = image;
        this.name = Html.fromHtml(currentContext.getResources().getString(R.string.colorcol)) + " COLOR: \n\t" + name;
        this.id = "MEANS: \n\t" +  id;
    }

您必須將類的實例化為

contents.add(new SetRows(this,inIconShow, sColor, sExplain)); 

當你做

getResources()

它的意思是

this.getResources()

是SetRows(您的類)的實例,您的SetRows類沒有名為getResources的方法。

這就是錯誤的含義。

getResources()是可用於所有擴展Context類的方法。 您的班沒有。

常見的解決方法是在創建SetRows對象時傳遞context的實例。

public SetRows(Context context, int image, String name, String id) {

        super();
        this.image = image;
        this.name = Html.fromHtml(context.getResources().getString(R.string.colorcol)) + " COLOR: \n\t" + name;
        this.id = "MEANS: \n\t" +  id;
    }

然后,在您的活動中,您可以執行以下操作:

new SetRows(this, /****/);

通過構造函數傳遞Context並調用:

context.getResources(...);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM