动态更改自定义操作栏上的 ImageView 源

Dynamically change an ImageView source on a custom action bar

我有一个使用 xml 的自定义操作栏。由于位置,我想动态更改左侧图像。该位置等于 switch 语句的大小写,所以这不是问题。我做错了什么?

    ImageView universityLogo;
    Global global = new Global();
    View v2 = View.inflate(this, R.layout.my_action_bar, null);
    universityLogo = (ImageView)v2.findViewById(R.id.buttonLeft);
    switch(global.getLocation()){
        case "33613":
            universityLogo.setImageResource(R.drawable.diploma);
    }
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowHomeEnabled(false);
    View mActionBarView = getLayoutInflater().inflate(R.layout.my_action_bar, null);
    actionBar.setCustomView(mActionBarView);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
}

和xml

<ImageButton
    android:id="@+id/buttonRight"
    android:layout_marginTop="10dp"
    android:layout_marginRight="10dp"
    android:layout_height="30dp"
    android:layout_width="30dp"
    android:layout_alignParentRight="true"
    android:background="@drawable/location"
    />
<ImageView
    android:id="@+id/buttonLeft"
    android:layout_marginTop="10dp"
    android:layout_marginRight="10dp"
    android:layout_height="30dp"
    android:layout_width="30dp"
    android:layout_alignParentLeft="true"
    />
<ImageView
    android:id="@+id/logo"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:src="@drawable/actionbarlogo"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>

为什么你用了下面这行两次?

 View mActionBarView = getLayoutInflater().inflate(R.layout.my_action_bar, null);

您设置视图并再次初始化它。你的代码应该如下所示

mageView universityLogo;
    Global global = new Global();
    View v2 = View.inflate(this, R.layout.my_action_bar, null);
    universityLogo = (ImageView)v2.findViewById(R.id.buttonLeft);
    switch(global.getLocation()){
        case "33613":
            universityLogo.setImageResource(R.drawable.diploma);
    }
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowHomeEnabled(false);

    actionBar.setCustomView(mActionBarView);
    actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);