繁体   English   中英

Android 导航抽屉,更改文本/悬停颜色

[英]Android navigation drawer, change text/hover color

我有两个关于提供 android studio 的导航抽屉模板的问题。

应用程序截图 )

我想更改菜单的文本颜色(“notre histoire”等)和所选项目的悬停(这里是绿色,我想让它变成其他颜色)。

如您所见,我设法更改了操作栏的背景颜色(此处为粉红色)并更改了菜单的背景(此处为蓝色)。

但在我的情况下,我没有找到如何更改文本颜色和所选项目的悬停。

我的限制是我不能接触 xml 文件。 我必须以编程方式进行。

这是我将菜单字符串提供给应用程序的方式:

String [] strTabMenu = new String[2];
strTabMenu[0] = "test1";
strTabMenu[1] = "test2";

mDrawerListView.setAdapter(new ArrayAdapter<String>(
                getActionBar().getThemedContext(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,
                strTabMenu));

那么,我现在如何使用一些代码行更改文本颜色和悬停颜色而不创建/更新一些 xml 文件?

谢谢=)

您可以编写自己的列表适配器,而不是使用android的默认ArrayAdapter:

public class DrawerListAdapter extends BaseAdapter{

private Context context;
private String[] mTitle;
private int[] mIcon;
private LayoutInflater inflater;

public DrawerListAdapter(Context pContext, String[] pTitle, int[] pIcon) {
    super();
    context = pContext;
    mTitle = pTitle;
    mIcon = pIcon;
}

public View getView(int position, View convertView, ViewGroup parent) {
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rootView = inflater.inflate(R.layout.navigation_drawer_list_item, parent, false);

    TextView txtTitle = (TextView) rootView.findViewById(R.id.drawer_text);
    ImageView imgIcon = (ImageView) rootView.findViewById(R.id.drawer_icon);

    if(((ListView)parent).isItemChecked(position)) {
            txtTitle.setTextColor(parent.getResources().getColor(R.color.DarkerRed));
    }
    txtTitle.setText(mTitle[position]);
    imgIcon.setImageResource(mIcon[position]);

    return rootView;
}

@Override
public int getCount() {
    return mTitle.length;
}

@Override
public Object getItem(int position) {
    return mTitle[position];
}

@Override
public long getItemId(int position) {
    return position;
}

}

现在,在if语句(isItemChecked)内部,可以更改文本视图的背景颜色。

要更改悬停项目背景,我必须更改主颜色、项目文本颜色,但是我可以更改它

// change hover text color
ColorStateList csl = new ColorStateList(
 int[][] {

new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_checked}  // checked 
},

new int[] {
getResources().getColor(R.color.color1, 
getTheme()), getResources().getColor(R.color.color2, getTheme())
});
        
navigationView.setItemTextColor(csl);
navigationView.setItemIconTintList(csl);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM