1

我使用 ListView 作为菜单,当您选择一个项目时,样式会更改以显示它已被选中,并且内容窗格也会更改。我的问题是我无法弄清楚如何“选择/更改第一个项目的样式”以显示它是默认选中的项目。我没有执行项目单击,因为此屏幕是用户在单击之前首先看到的。我在 onActivityCreated 和 onStart 中尝试过 getListView().getChildAt(0) 但它总是返回 null。我也试过调用listView.performItemClick()。下面是代码,您可以在我的自定义 MenuAdapter 中看到我当前的 hack 解决方案。我觉得我错过了一些简单的东西,因为似乎很多应用程序都想要这样做。感谢您的任何帮助!

public class FixItActionListFragment extends ListFragment {
    // The last menu item selected 
    View lastRow = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Defined the list of actions in the file strings.xml
        String[] fixItActions = getResources().getStringArray(R.array.fixItActions);

        setListAdapter(new MenuAdapter(getActivity(), fixItActions));
    }

    /**
     * Inflate the layout for the action list fragment
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        // Inflate the layout for the action list fragment
        View v =  inflater.inflate(R.layout.fixitactionlistfragment, container, false);
        return v;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
                // this isn't working
        //ListView listview = getListView();
        //View view = listview.getAdapter().getView(0, null, null);
        //long rowId = listview.getAdapter().getItemId(0);
        //listview.performItemClick(view, 0, rowId);
    }

    /**
     * Called when a action item is selected
     */
    public void onListItemClick(ListView parent, View view, int position, long id) {
        // Change the style of the selected item and revert the last item
        if (lastRow != null) {
            // Set the previous selected row to unselected  
                        ...
        }
            // Set current item to selected
            ...
        lastRow = view;

    }

    class MenuAdapter extends ArrayAdapter<String> {

        MenuAdapter(Context context, String[] actions) {
            super(context, R.layout.menu_row, R.id.menuItem, actions);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // Get the selected row
            View row = super.getView(position, convertView, parent);
            // HACK!!!!  If it's the first item, then mark as selected
            if (lastRow == null) {
                lastRow = row;
                TextView thisItem = (TextView) row.findViewById(R.id.menuItem);
                thisItem.setTextColor(getResources().getColor(R.color.menuItemSelected));               
            }
            return row;         
        }
    }
}
4

0 回答 0