I am writing an android app in which I am trying to change the color of the title of Action Bar by clicking on Button. As soon as, I click the button , the title gets hidden though I am passing the color code of YELLOW. Here is my Code of MainActitvity.java
Button B;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
B = (Button) findViewById(R.id.button1);
B.setOnClickListener(this);
}
public void onClick(View v) {
android.app.ActionBar actionBar = getActionBar();
Internal.setActionBarTitleColor(actionBar, 256);
}
Internal.java
public static void setActionBarTitleColor(android.app.ActionBar actionBar, int titleColor) {
if(actionBar == null)
return;
try {
Field actionViewField = actionBar.getClass().getDeclaredField("mActionView");
actionViewField.setAccessible(true);
Object actionView = actionViewField.get(actionBar);
if(actionView == null)
return;
Field titleTextField = actionView.getClass().getDeclaredField("mTitleView");
titleTextField.setAccessible(true);
TextView titleText = (TextView)titleTextField.get(actionView);
if(titleText != null)
titleText.setTextColor(titleColor);
} catch (Exception e) {
e.printStackTrace();
}
}
actionBar.setBackgroundDrawable(new ColorDrawable(0xff00DDED));
actionBar.setDisplayShowTitleEnabled(false); // required to force redraw
actionBar.setDisplayShowTitleEnabled(true);
int titleId=Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
TextView yourTextView = (TextView)findViewById(titleId);
yourTextView.setTextColor(getResources().getColor(R.color.white));
The ActionBar title ID is hidden, or in other words, it's internal and accessing it can't be done typically. You can reference it using Resources.getIdentifier.
Follow the step below:
1. Grab the ID for the action_bar_title
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
2. Now you can use the ID with a TextView
TextView abTitle = (TextView) findViewById(titleId);
abTitle.setTextColor(colorId);
That's all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.