在Fragment列表中初始调用setItemChecked不起作用

时间:2014-08-07 06:32:30

标签: android listview android-fragments android-lifecycle

我正在尝试选择列表片段onCreateView中的项目。我这样做如下:listView.setItemChecked(position, true);。很遗憾,视图未激活,因为我的ArrayAdapter getView永远不会被调用,因此我无法修改已选中的项目。任何建议或链接都​​表示赞赏!

碎片onCreateView

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View layout=  inflater.inflate(
            R.layout.fragment, container, false);

    mListView= (ListView) layout.findViewById(R.id.navigation_list);


    mListView.setAdapter(new Adapter(
            this,
            R.layout.list_item,
            titles));
    mListView.setItemChecked(mCurrentSelectedPosition, true);

    return layout;
}

ArrayAdapter

public class Adapter extends ArrayAdapter<String> {

private Activity mActivity;
private int mResource;

public Adapter(Fragment fragment, int resource, ArrayList<String> titles) {
    super(fragment.getActivity(), resource, titles);
    mActivity = fragment.getActivity();
    mResource = resource;
}

@Override
public View getView(int position, View convertView, ViewGroup parent){
    ViewHolder holder;

    if(convertView == null){
        convertView = mActivity.getLayoutInflater().inflate(mResource, parent, false);

        holder = new ViewHolder();
        holder.title = (TextView)convertView.findViewById(R.id.title);

        convertView.setTag(holder);
    }
    else{
        holder = (ViewHolder)convertView.getTag();
    }

    holder.title.setText(getItem(position));
    holder.title.setTypeface(null, convertView.isActivated() ? Typeface.BOLD : Typeface.NORMAL);

    return convertView;
}

private class ViewHolder{
    private TextView title;
}
}

修改的 以下代码在检测激活时出于某种原因正常工作,为什么我的自定义适配器不起作用?

listView.setAdapter(new ArrayAdapter<String>(
            getActionBar().getThemedContext(),
            android.R.layout.simple_list_item_activated_1,
            android.R.id.text1,
            new String[]{
                    "ONE",
                    "TWO"
            }));

1 个答案:

答案 0 :(得分:1)

您需要在choiceMode

中使用setItemChecked之前设置ListView

<强>样品:

mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); 
mListView.setItemChecked(mCurrentSelectedPosition, true);

编辑:

如果要在检查项目后刷新列表视图中的视图,请同时调用mListView.notifyDataSetChange();

编辑:2

创建一个类

public class StringWrapper{ 
public String string; 
public boolean isBold = false; 
}

将该类用作String

的包装器

并更改此

更改此title.setTypeface(null, title.isActivated() ? Typeface.BOLD : Typeface.NORMAL);

title.setTypeface(null, titles.get(position).isBold ? Typeface.BOLD : Typeface.NORMAL);

并更改此内容:mListView.setItemChecked(mCurrentSelectedPosition, true);

titles.get(mCurrentSelectedPosition).isBold = true
mListView.notifyDataSetChange();