简体   繁体   中英

Making selected item bold in navigation drawer, but can't get the first item to be bold when the app starts

So I'm trying to make the selected item's text bold in the navigation drawer (like Google Play apps), but I can't get the first item to be bold when first starting the app This is what I'm using to make it work

private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            setNavDrawerItemNormal();
            TextView TV = (TextView) view.findViewById(R.id.text1);
            TV.setTypeface(null, Typeface.BOLD);
            selectItem(position);
        }
    }

    public void setNavDrawerItemNormal() {
        for (int i = 0; i < mDrawerList.getChildCount(); i++) {
            View view = mDrawerList.getChildAt(i);
            TextView TV = ((TextView) view.findViewById(R.id.text1));
            TV.setTypeface(null, Typeface.NORMAL);
        }
    }

I tried adding this in the onCreate() method, but it throws an error because of the second line

View view = mDrawerList.getChildAt(0);
TextView TV = (TextView) view.findViewById(R.id.text1);
TV.setTypeface(null, Typeface.BOLD);

The LogCat says the it's caused by java.lang.NullPointerException Any idea why this is happening? And how to make it work?

The problem is because mDrawerList.getChildAt(0) returns the first visible child, not the first item in the list.

You may want to achieve your result in the getView() method of your adapter class:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ...

    if(position == 0) {
        // set bold text here
    }

    ...
}

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.

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