为什么这个putExtra传递的是String而不是int?

时间:2015-01-19 17:11:31

标签: android android-intent

我想通过意图将R.drawable id传递给另一个活动。我正在使用开关找到正确的drawable,然后使用putExtra()传递它。但是当我调用getIntExtra时,它说我传递了一个String。这段代码有问题还是在其他地方?

int i = getExerciseId(((TextView)getView().findViewById(R.id.fragTextView)).getText().toString());
            Intent intent = new Intent(v.getContext(), LevelActivity.class);
            intent.putExtra("exerciseId", ((TextView)getView().findViewById(R.id.fragTextView)).getText().toString());
            intent.putExtra("image", i);
            startActivity(intent);
        }

        public int getExerciseId(String s) {
            int i = -1;
            switch (s) {
                case "Weather":
                    i = R.drawable.weather;
                break;
                case "Weekend":
                    i = R.drawable.weekend;
                break;
                case "Hobbies":
                    i = R.drawable.hobbies;
                break;
                case "Music":
                    i = R.drawable.music;
                break;
                case "Family":
                    i = R.drawable.family;
            }
            return i;

编辑:没有日志错误,我在代码中看到一条红线消息:

getIntExtra(String, int) in Intent cannot be applied to (String)

在这行代码中:

intent.getIntExtra("image");

3 个答案:

答案 0 :(得分:4)

它没有告诉您正在获取字符串,但是您使用参数不足调用getIntExtra方法。用

调用它
getIntExtra("image", 0); // or whichever default value you want to use.

答案 1 :(得分:3)

getIntExtra(String name, int defaultValue)

您必须为方法调用提供默认值。如果未找到密钥,则返回默认值。

http://developer.android.com/reference/android/content/Intent.html#getIntExtra(java.lang.String,%20int)

答案 2 :(得分:1)

获取int值

 //wirte name=imge and defaultValue =-1
 //and have a check if value for image is -1 then no value was received

 intent.getIntExtra(name, defaultValue);