根据在微调器中选择的值设置imageView src

时间:2017-12-22 12:57:08

标签: java android spinner

我一直在尝试根据从Spinner中选择的值设置ImageView(默认为空)。 所以在mainActivity.java

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

    sp_home = (Spinner) findViewById(R.id.spinner_home_team);
    sp_away = (Spinner) findViewById(R.id.spinner_away_team);


    sp_home.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                   int arg2, long arg3) {
            if (!sp_home.getSelectedItem().toString().equals("Seleziona Squadra")) {
                setTeamLogo(sp_home.getSelectedItem().toString(), "home");
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

    sp_away.setOnItemSelectedListener(new OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                                   int arg2, long arg3) {
            if (!sp_away.getSelectedItem().toString().equals("Seleziona Squadra")) {
                setTeamLogo(sp_away.getSelectedItem().toString(), "away");
            }
        }

        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }
    });

}

当我在setTeamLogo中执行代码时,setOnItemSelectedListener方法完美地解决了问题。

private void setTeamLogo(String teamName, String home_or_away_team){

    int resId = getResources().getIdentifier(teamName, "drawable", getPackageName());
    Toast.makeText(getBaseContext(), resId,
            Toast.LENGTH_LONG).show();


}

抛出的异常是: android.content.res.Resources $ NotFoundException:字符串资源ID#0x0

任何想法为什么如果我使用图像的名称而不是变量teamName一切都很完美?

1 个答案:

答案 0 :(得分:1)

使用String.valueOf()

如果你传递一个整数,它将尝试查找相应的字符串资源ID - 它找不到,这是你的错误。

看看这篇文章: -

android.content.res.Resources$NotFoundException: String resource ID #0x0