字符串中的颜色解析错误

8

编辑:我的项目相关部分的Pastebin:

这里是更新后的代码

此外,ColouredItem是一个包装器:

     public class ColouredItem
     {//Only a wrapper class,no behaviour has been defined here
        String name,colour;
     }

使用以下代码将字符串解析为颜色时,我遇到了NumberFormatException异常:

     row.setBackgroundColor(Color.parseColor(item.colour));

我使用以下内容从资源创建项目列表:
```html

我使用以下内容从资源创建项目列表:

```
    for(int i=0;i<list.length;i++)
    {
        item=new ColouredMenuItem();
        String[] cmenu =list[i].split("#");
        item.name=cmenu[0];
        item.colour="#"+cmenu[1];
        Log.d(TAG, item.colour);
        menuList.add(item);
    }

我遇到的异常是...我发现view.setBackgroundColor只接受整数值:

         #ffffff 
         #ffffBB 
         #fff45f 
         #ffff00 
         Shutting down VM
         threadid=1: thread exiting with uncaught exception (group=0x4001d800)
         FATAL EXCEPTION: main
             java.lang.NumberFormatException: ffffff 
         at java.lang.Long.parse(Long.java:364)
         at java.lang.Long.parseLong(Long.java:354)
         at android.graphics.Color.parseColor(Color.java:207)
         at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
         at android.widget.AbsListView.obtainView(AbsListView.java:1315)
         at android.widget.ListView.makeAndAddView(ListView.java:1727)
         at android.widget.ListView.fillDown(ListView.java:652)
         at android.widget.ListView.fillFromTop(ListView.java:709)
         at android.widget.ListView.layoutChildren(ListView.java:1580)
         at android.widget.AbsListView.onLayout(AbsListView.java:1147)
         at android.view.View.layout(View.java:7035)
         at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
         at android.view.View.layout(View.java:7035)
         at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
         at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
         at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
         at android.view.View.layout(View.java:7035)
         at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
         at android.view.View.layout(View.java:7035)
         at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
         at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
         at android.os.Handler.dispatchMessage(Handler.java:99)
         at android.os.Looper.loop(Looper.java:123)
         at android.app.ActivityThread.main(ActivityThread.java:4627)
         at java.lang.reflect.Method.invokeNative(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:521)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
         at dalvik.system.NativeStart.main(Native Method)

像一些答案所建议的那样添加 # 并没有解决问题:

          java.lang.NumberFormatException: Invalid long: "#ffffff"
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
      at android.app.ActivityThread.access$600(ActivityThread.java:141)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
      at android.os.Handler.dispatchMessage(Handler.java:99)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:5103)
      at java.lang.reflect.Method.invokeNative(Native Method)

这个实现方式也没有任何区别:

          String cmenu=list[i];
          item.name=cmenu.substring(0, cmenu.indexOf("#"));
          item.colour=cmenu.substring(cmenu.indexOf("#"));

Android提供了一种复杂的方法来从字符串中解析颜色Color.parseColor("#ffffff"),你试过了吗? - vinay kumar
我确实使用过 int Color.parseColor(string)。 - vamsiampolu
当你可以使用item.colour=list[i]时,这个"item.colour="#"+cmenu[1];"的用途是什么? - vinay kumar
我需要从一个较大的字符串中提取颜色,实际上list[i]返回很多单词#ffffff - vamsiampolu
你能展示一下 ColouredMenuItem.java 文件吗? - vinay kumar
显示剩余2条评论
4个回答

12

使用以下代码:

row.setBackgroundColor(Color.parseColor("#424242"));

它也对我有帮助,不要去掉“#”。

我使用了这段代码。

private List<String> item;

item = new ArrayList<String>();
item.add("#424242");
row.setBackgroundColor(Color.parseColor(item.get(0)));

它对我而言运作良好,也许你的分割函数不太好用

或者是你的代码出了问题

Button btn;
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[] { "Page1 #ffffff", "Page2 #ffffBB" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.sample);

    try {
        btn = (Button) findViewById(R.id.button1);
        for (int i = 0; i < list.length; i++) {
            item = new ColouredMenuItem();
            String[] cmenu = list[i].split("#");
            item.name = cmenu[0];
            item.color = "#" + cmenu[1];
            Log.d("colored", item.color);
            menuList.add(item);
        }



        btn.setBackgroundColor(Color.parseColor(menuList.get(1).color));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

我这边的情况很好

这是新代码

将您的彩色项目制作为一个类似于以下getter和setter的bean类

public class ColouredMenuItem {// Only a wrapper class,no behaviour has been defined
                        // here
String name, colour;

List<ColouredMenuItem> list=new ArrayList<ColouredMenuItem>();

public List<ColouredMenuItem> getList() {
    return list;
}

public void setList(List<ColouredMenuItem> menuList) {
    this.list = menuList;
}

public String getName() {
    return name;
}

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

public String getColour() {
    return colour;
}

public void setColour(String colour) {
    this.colour = colour;
}

}

然后在您的适配器中使用此代码。

try {
        Log.d(TAG, menuList.get(position).colour);
        textView.setText(menuList.get(position).getName());

        {
            row.setBackgroundColor(Color.parseColor(menuList.get(position).getColour()));
        }
    } catch (Exception ex) {
        Log.e(TAG, "Still does not work");
    }

只需试一试,在我的这一侧它可以工作

您的数组就是这样

<string-array name="menu_array">
    <item>Page1 #ff7788</item>
    <item>Page1 #ff6688</item>
    <item>Page1 #424242</item>
</string-array>

日志记录的前四行看起来有点暗淡,实际上是这样的。 String[] cmenu =list[i].split("#"); item.name=cmenu[0]; item.colour="#"+cmenu[1]; - vamsiampolu
1
首先尝试使用像我的硬编码值一样的值,如果可以工作,那么可能是您的分割出现了问题。 - Meenal
使用硬编码的值进行了工作,但即使添加了 #,它仍然无法正常工作。 - vamsiampolu
请检查更新后的代码,我的适配器(MyAdapter)是否有问题,或者是我不能在那里使用Color.parseColor。它可以很好地处理硬编码字符串,但是当我使用位置传递时似乎存在问题。请查看帖子顶部的编辑... - vamsiampolu
好的,我明白你的问题了。我已经按照你的要求完成了,并在此处粘贴了新代码。 - Meenal
显示剩余4条评论

0

查看堆栈跟踪,它会告诉你:

 java.lang.NumberFormatException: ffffff  
     at java.lang.Long.parse(Long.java:364)
     at java.lang.Long.parseLong(Long.java:354)
     at android.graphics.Color.parseColor(Color.java:207)
     at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)

逐行:

you are trying to format Hexadecimal (base 16) value "0xffffff" to a decimal (base 10) value
you're trying to parse hexadecimal string "ffffff" to type Long
same as above.
error is thrown when calling `Color.parseColor()`
error is thrown from your MadAdapter.java Class on line 60.

所以,你需要找到一种从十六进制而不是十进制值解析它的方法。十六进制值通常以0x [value]或#[value]开头。


0
假设:在从字符串对象“item”解析颜色时,不是从列表数组中获取,而是从ColoureMenuItem的实例变量中获取。
    ColouredMenuItem item;
        ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
        String[] list = new String[]{"#ffffff","#00ffff"};





// parsing your string here, no change in this
for(int i=0;i<list.length;i++)
            {
                item=new ColouredMenuItem();
                String[] cmenu =list[i].split("#");
                item.name=cmenu[0];
                item.color="#"+cmenu[1];
                Log.d("colored", item.color);
                menuList.add(item);
            }

// 确认数值是否被解析。

            for(int i=0;i<menuList.size();i++)
            {
                int color = Color.parseColor(menuList.get(i).color);
                Log.d("color",""+menuList.get(i).color);
            }

以及你的 ColouredMenuItem 类。

public class ColouredMenuItem {

    public String color;
    public String name;

}

把它想象成 String[] list= {"Page1 #ffffff","Page2 #ffffBB"}; 而不是你所拥有的变量。它可以使用硬编码的字符串工作,但似乎在这里无法正常工作。 - vamsiampolu

0
尝试使用Color.parseColor("#ffffff");代替Color.parseColor("ffffff");

为了获取颜色值,我使用类似于名称颜色并在#处分割的方式:item.name=cmenu[0];``item.colour="#"+cmenu[1]; 日志记录的前四行表示解析后获得的颜色字符串值。 - vamsiampolu
因为该字符串看起来像是“Page 1 #ffffff”。 - vamsiampolu
你必须在颜色十六进制值前添加一个“#”,例如“ffffff”必须写成“#ffffff”,否则它将无法正常工作。 - johntheripp3r
我已经发布了添加#的结果。我认为我做错了一些简单的事情。我已经在pastebin中发布了整个代码...请查看帖子顶部的编辑。 - vamsiampolu
是的,在pastebin上我已经粘贴了一个logcat,其中字符串“#ffff45”在传递给“Color.parseColor”时返回值“-187”。 - vamsiampolu
不需要在意整数值,只需尝试设置颜色。 - johntheripp3r

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接