导航抽屉中的选定项目

时间:2014-01-04 20:15:59

标签: android navigation-drawer

我在我的应用中实现了导航抽屉(http://developer.android.com/training/implementing-navigation/nav-drawer.html)。

如何更改实际选定项目的显示?我希望所选项目是粗体和不同的颜色。

在官方示例中,他们使用" setItemChecked",但是如何修改单个选中项的方面? " setOnItemSelectedListener"方法不起作用。

到目前为止,我打开片段时所做的就是这段代码:

for (int i = 0; i < mDrawerList.getChildCount(); i++){
    TextView t = (TextView) mDrawerList.getChildAt(i);

    if(i == fragmentPosition) t.setTextColor(getResources().getColor(R.color.blue));
    else t.setTextColor(getResources().getColor(R.color.black));
}

它有效,但在应用启动时,没有选择任何项目,我也无法设置任何项目,因为列表视图尚未创建(当我们第一次打开它时创建它,我想)。

我尝试创建一个选择器,但不知道如何正确设置不同的属性(选中项目,选择项目,项目点击??),搜索文档但我不明白。

感谢您提供的任何帮助!

2 个答案:

答案 0 :(得分:4)

我会在适配器中做到这一点。

mAdapter.setSelectedItem(position);

public View getView(...) {
    ...
    if (position == mSelectedItem) {
        text.setTypeface(...);
        text.setBackgroundColor(...);
    } else {
        text.setTypeface(...);
        text.setBackgroundColor(...);
    }
}

如果您不需要设置字体,可以使用选择器

setTextColor(@drawable/my_selector).

或者使用TextView将其放入xml文件

android:textColor="@drawable/my_selector"

答案 1 :(得分:1)

这是我改变导航抽屉中所选项目的颜色和字体的解决方案......

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
     setNavDrawerItemNormal();
     TextView txtview = ((TextView) view.findViewById(R.id.txtNav));
     txtview.setTypeface(null, Typeface.BOLD);
     txtview.setTextColor(R.color.Red);
}

public void setNavDrawerItemNormal()
{
    for (int i=0; i< mDrawerListView.getChildCount(); i++)
    {
        View v = mDrawerListView.getChildAt(i);
        TextView txtview = ((TextView) v.findViewById(R.id.txtNav));
        Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Light.ttf");
        txtview.setTypeface(font);
        txtview.setTextColor(R.color.Red);
    }
}

在初始化应用程序时加粗导航抽屉中的第一项,我在列表适配器获取视图方法中做了...

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.navdrawer_item, parent, false);
    TextView textView = (TextView) rowView.findViewById(R.id.txtNav);
    textView.setText(values[position]);
    if (position == 0) 
    { 
       textView.setTypeface(null, Typeface.BOLD);
       textView.setTextColor(R.color.Red);
    }

    return rowView;
}

所以,在这里我检查了项目的位置是否为0(意味着它是第一项),然后将其设为粗体。整件事对我来说很完美!〜

相关问题