在{try / catch}语句和Color类中获取错误

时间:2014-08-19 03:13:34

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

我试图创建一个应用程序,用户可以在其中输入十六进制颜色到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)

2 个答案:

答案 0 :(得分:0)

尝试替换代码的和平:

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

答案 1 :(得分:0)

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

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

如果要在用户输入时完成更改背景的效果,则必须使其传递给parseColor的String始终是有效的十六进制。

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