使用以前版本的 AppCompat 可以很容易地获取 ActionBar
的标题 TextView 并对其进行修改。
这是我使用的方法:
private TextView getActionBarTitleView() {
int id = getResources().getIdentifier("action_bar_title", "id", "android");
return (TextView) findViewById(id);
}
然后更改标题的 alpha 值:
getActionBarTitleView().setAlpha(ratio*255);
现在由于某些原因,最新 AppCompat 版本的“action_bar_title”不再起作用。当我尝试使用我的方法时,它返回给我“null”。尝试使用 ActionBar
的其他 ID,但没有找到合适的 ID。
我在 StackOverflow 上看到了 Ahmed Nawara 的 1 篇文章,他目前找到的唯一方法是对 Toolbar
的 subview 进行迭代,并且每当 TexView
找到,将它的文本值与 toolbar.getTitle() 进行比较,以确保这是我们正在查看的 TexView
。
如果有人可以帮助我将此解决方案集成到我的案例中,因为我实际上不知道该怎么做。
最佳答案
我猜你是从 Flavien Laurent's post 得到你的方法的让 ActionBar 不乏味。如果您仔细观察,他详细介绍了另一种设置 ActionBar 标题的 alpha 的技术,其灵感来自 Cyril Mottier。
它使用自定义 AlphaForegroundColorSpan
类扩展 ForegroundColorSpan
:
public class AlphaForegroundColorSpan extends ForegroundColorSpan
{
private float mAlpha;
public AlphaForegroundColorSpan(int color)
{
super(color);
}
public AlphaForegroundColorSpan(Parcel src)
{
super(src);
mAlpha = src.readFloat();
}
public void writeToParcel(Parcel dest, int flags)
{
super.writeToParcel(dest, flags);
dest.writeFloat(mAlpha);
}
@Override
public void updateDrawState(TextPaint ds)
{
ds.setColor(getAlphaColor());
}
public void setAlpha(float alpha)
{
mAlpha = alpha;
}
public float getAlpha()
{
return mAlpha;
}
private int getAlphaColor()
{
int foregroundColor = getForegroundColor();
return Color.argb((int) (mAlpha * 255), Color.red(foregroundColor), Color.green(foregroundColor), Color.blue(foregroundColor));
}
}
然后,使用 SpannableString
,您只需将 alpha 设置为 AlphaForegroundColorSpan
,然后将此 AlphaForegroundColorSpan
设置为 SpannableString
:
public void onCreate(Bundle savedInstanceState)
{
...
spannableString = new SpannableString("ActionBar title");
alphaForegroundColorSpan = new AlphaForegroundColorSpan(0xffffffff);
...
}
private void setActionBarTitle(int newAlpha)
{
alphaForegroundColorSpan.setAlpha(newAlpha);
spannableString.setSpan(alphaForegroundColorSpan, 0, spannableString.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
getSupportActionBar().setTitle(spannableString);
}
希望对您有所帮助。如果还不够清楚,再看看 Flavient Laurent 的帖子!
关于android - AppCompat v7 r21 更改 ActionBar 标题的 Alpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26572164/