在ListView中选择初始项以更改样式

时间:2012-04-12 16:24:50

标签: android listview

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

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;         
        }
    }
}

0 个答案:

没有答案