Andrew Nguyen Andrew Nguyen - 15 days ago 7
Android Question

Dynamically change an ImageView source on a custom action bar

I have a working custom action bar using an xml. I want to dynamically change the left image due to the location. The location equals the case of the switch statement so that's not the issue. What am I doing incorrectly?

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);
}


and 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>

Answer

Why you used below line twice?

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

you set up view and again initialize that again. you code should like below

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);