Mahab
Mahab

Reputation: 198

Set text for a TextView in a layout coming from LayoutInflator

I'm making a custom action bar layout, and I want to reuse it in all activities. For that I want to be able to set the title in the action bar layout to the activity title,

View actionBarView =LayoutInflater.from(senderActivity.getApplicationContext()).inflate(R.layout.az_actionbar, null);
((TextView)actionBarView.findViewById(R.id.azActionBar_tv_title)).setText("tetetete");

But the TextView doesn't change its text (doesn't show "tetetetete")

Any ideas why is this happening? or is there a better way to apply the custom ActionBar layout globally?

The method I used to customize the actionbar.

Java code of the helper method that is being called on onCreate from each activity with Helper.setAzCustomActionBar(this):

public static void setAzCustomActionBar(AppCompatActivity sender){

    //getting the activity title
    String title;
    try {
        ActivityInfo activityInfo = sender.getPackageManager().getActivityInfo(
                sender.getComponentName(), PackageManager.GET_META_DATA);
        title = activityInfo.loadLabel(sender.getPackageManager())
                .toString();
    } catch (PackageManager.NameNotFoundException e) {
        title = "abcd";
    }


    View actionBarView = LayoutInflater.from(sender.getApplicationContext()).inflate(R.layout.az_actionbar, null);
    //This is the line that doesn't work
    ((TextView) actionBarView.findViewById(R.id.azActionBar_tv_title)).setText(title);
    sender.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    sender.getSupportActionBar().setCustomView(R.layout.az_actionbar);
}

Upvotes: 0

Views: 149

Answers (2)

Shmuel
Shmuel

Reputation: 3916

"or is there a better way to apply the custom ActionBar layout globally?"

Yes. The best way is to use the Toolbar widget.

android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:minHeight="?attr/actionBarSize"
android:background="#2196F3"
android:layout_width="match_parent"
android:layout_height="wrap_content"

This answer talks about it - Android Lollipop Toolbar vs Custom view

https://chris.banes.me/2014/10/17/appcompat-v21/

http://javatechig.com/android/android-lollipop-toolbar-example

https://blog.xamarin.com/android-tips-hello-toolbar-goodbye-action-bar/

Upvotes: 0

Tudor Luca
Tudor Luca

Reputation: 6419

You have to set the "changed" custom view as a custom view for the action bar.

Change sender.getSupportActionBar().setCustomView(R.layout.az_actionbar); to sender.getSupportActionBar().setCustomView(actionBarView);

Upvotes: 1

Related Questions