TextView on Action Bar

2019-04-16 19:29发布

问题:

I am trying to add a textView on the actionBar which I can dynamically edit. Why is the below code not working????

<?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android" 
        android:id="@android:id/text1"
        style="@style/TextMedium"
        android:paddingLeft="5dp"
        android:singleLine="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee" />

In the onCreate method of activity,

View addView = getLayoutInflater().inflate(R.layout.spinner_select_text, null);
        actionBar.setCustomView(addView,new ActionBar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        TextView label =  (TextView)addView.findViewById(android.R.id.text1);
        label.setText("Hello");

回答1:

You also need actionBar.setDisplayShowCustomEnabled(true);

FYI you can give the action bar your layout id instead of inflating it yourself:

    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(R.layout.spinner_select_text);

    TextView label = (TextView) actionBar.getCustomView().findViewById(android.R.id.text1);