【问题标题】:Getting error during while { try/catch } statement, and Color class在 while { try/catch } 语句和 Color 类期间出现错误
【发布时间】:2014-10-12 01:36:51
【问题描述】:

我正在尝试制作一个应用程序,用户可以在其中将十六进制颜色输入到 EditText 中,然后按一个按钮来更改应用程序的背景。我设法让它工作,但现在我正在尝试让它在用户输入文本框时改变背景颜色,然后他们可以按下按钮进行设置。

这是我的主要活动课程的开始,我的所有编程都在这里:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Assign variables to widgets
    final Button addToPalette = (Button) findViewById(R.id.Button_addToPalette);
    final RelativeLayout layoutMain = (RelativeLayout) findViewById(R.id.layout_main);
    final EditText editText_HEX = (EditText)findViewById(R.id.EditText_HEX);
    String stringHEX = editText_HEX.getText().toString();
    boolean correctInput = false;


    // Loop until a valid color background is achieved

    while (!correctInput) {
        try {

            layoutMain.setBackgroundColor(Color.parseColor(stringHEX));
            correctInput = true;
        }catch (InputMismatchException e){

        }


    }



    /** ----- Button click changes background color of relative layout -------
     * ------- This came first (and it works) , and I decided to try the while try/catch statement above so I made
     * -------- this code all comments so it won't interfere.
    addToPalette.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Convert editTextHEX to a string
            String stringHEX = editText_HEX.getText().toString();

            // Check for #, and if not found, add one
            if (stringHEX.contains("#")) {
                layoutMain.setBackgroundColor(Color.parseColor(stringHEX));
                Toast.makeText(getApplicationContext(), stringHEX + " added to palette.", Toast.LENGTH_SHORT).show();
            }else {
                stringHEX = "#" + stringHEX;
                layoutMain.setBackgroundColor(Color.parseColor(stringHEX));
                Toast.makeText(getApplicationContext(), stringHEX + " added to palette.", Toast.LENGTH_SHORT).show();
            }
        }

    });
    */

}

我以前从未使用过 try/catch 语句,但它似乎足够东方。我在这里读到了:http://goo.gl/X2I4mA

我在 try 语句中遇到错误:

layoutMain.setBackgroundColor(Color.parseColor(stringHEX));

但是,当这一行在按钮 onClick() 代码中时,它可以正常工作。

如果您想查看我的(简单)布局,或者如果它有帮助,这里是我的 activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<EditText
    android:id="@+id/EditText_HEX"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="100dp"
    android:text="#"
    android:cursorVisible="true"
    android:textAllCaps="true"
    android:inputType="textCapCharacters"
    android:maxLength="7"/>
<Button
    android:id="@+id/Button_addToPalette"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:text="Add To Palette"
    android:layout_centerHorizontal="true"
    android:layout_below="@+id/EditText_HEX"
    android:layout_marginTop="5dp"/>


</RelativeLayout>

我是 Android 新手。感谢您的帮助!

编辑:使用 logcat 更新:

08-19 00:12:40.341  11352-11352/com.example.colorclass E/Trace﹕ error opening trace file: No such       file or directory (2)
08-19 00:12:40.341  11352-11352/com.example.colorclass D/ActivityThread﹕ setTargetHeapUtilization:0.25
08-19 00:12:40.341  11352-11352/com.example.colorclass D/ActivityThread﹕ setTargetHeapIdealFree:8388608
08-19 00:12:40.341  11352-11352/com.example.colorclass D/ActivityThread﹕ setTargetHeapConcurrentStart:2097152
08-19 00:12:40.451  11352-11352/com.example.colorclass W/AllCapsTransformationMethod﹕ Caller did   not enable length changes; not transforming text
08-19 00:12:40.451  11352-11352/com.example.colorclass W/AllCapsTransformationMethod﹕ Caller did not enable length changes; not transforming text
08-19 00:12:40.461  11352-11352/com.example.colorclass W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40c4a438)
08-19 00:12:40.471  11352-11352/com.example.colorclass E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity     ComponentInfo{com.example.colorclass/com.example.colorclass.MainActivity}:     java.lang.NumberFormatException: Invalid long: ""
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2080)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2105)
        at android.app.ActivityThread.access$600(ActivityThread.java:133)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1211)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4795)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NumberFormatException: Invalid long: ""
        at java.lang.Long.invalidLong(Long.java:125)
        at java.lang.Long.parseLong(Long.java:346)
        at android.graphics.Color.parseColor(Color.java:208)
        at com.example.colorclass.MainActivity.onCreate(MainActivity.java:37)
        at android.app.Activity.performCreate(Activity.java:5008)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2044)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2105)
        at android.app.ActivityThread.access$600(ActivityThread.java:133)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1211)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4795)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
        at dalvik.system.NativeStart.main(Native Method)

【问题讨论】:

  • 可以贴出错误的堆栈跟踪吗?
  • soundsofpolaris,我继续复制了 logcat。如果这不是堆栈跟踪的内容,请告诉我。谢谢。

标签: android colors while-loop hex try-catch


【解决方案1】:

问题是您没有将有效的String 传递给Color.parseColor()。注意在logcat中,错误最后说: java.lang.NumberFormatException: Invalid long: ""

发生的情况是,一旦创建了 Activity,就会调用 onCreate,它会从 editText_HEX EditText 中获取输入。问题是,第一个字符串是空的。当您进入 while 循环时,它传递了一个空字符串。

如果你想实现在用户输入时改变背景的效果,你必须使传递给 parseColor 的字符串始终是有效的十六进制。

编辑: 简单的方法是根据正则表达式检查字符串:http://www.mkyong.com/regular-expressions/how-to-validate-hex-color-code-with-regular-expression/ 如果失败,请不要设置颜色。困难的方法是解析用户输入的任何内容,然后用缺少的有效值重建字符串。因此,如果用户键入#ff,则需要填写其余部分,例如 #ff0000。

【讨论】:

  • 谢谢,正则表达式实用程序正是我想要的。我尝试了代码,有点困惑。经过快速的谷歌搜索后,我想出了这个:“Boolean isHex = stringHEX.matches("^#([A-Fa-f0-9]{6})$");”,这给了我一个真/假(一个非常简单的陈述,哈哈)。感谢您将我引向正确的方向。
【解决方案2】:

尝试替换这段代码:

try {
    layoutMain.setBackgroundColor(Color.parseColor(stringHEX));
    correctInput = true;
}catch (Throwable e){
   e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多