在Android中选择具有MultiChoice选项的ListView

时间:2016-10-26 06:43:39

标签: android listview multi-select

我正在尝试下面的代码

<div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li class='@Html.IsActive("Home", "Index")'>
            @Html.ActionLink("Home", "Index", "Home")
        </li>
        <li class='@Html.IsActive("Home", "About")'>
            @Html.ActionLink("About", "About", "Home")
        </li>
        <li class='@Html.IsActive("Home", "Contact")'>
            @Html.ActionLink("Contact", "Contact", "Home")
        </li>
    </ul>
</div>

这会按照原始public class MainActivity extends Activity { private ListView list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final String[] items = { "item 1", "item 2", "item 3", "item 4", "item 5", "item 6", "item 7" }; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, items); list = (ListView) findViewById(R.id.list); list.setAdapter(adapter); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String checkedItems = displayCheckedItems(list .getCheckedItemPositions()); Toast.makeText(getApplicationContext(), checkedItems, Toast.LENGTH_SHORT).show(); } }); } /** * The method checks the SparseBooleanArray in order to return String * representation with the names of the checked items * * @param checkedItems * @return String */ private String displayCheckedItems(SparseBooleanArray checkedItems) { StringBuffer sb = new StringBuffer(""); for (int i = 0; i < checkedItems.size(); i++) { if (checkedItems.valueAt(i)) { int idx = checkedItems.keyAt(i); if (sb.length() > 0) sb.append(", "); String s = (String) list.getAdapter().getItem(idx); sb.append(s); } } return sb.toString(); } }

中的顺序为我提供所选项目

但是我希望按照我选择的顺序获取项目

例如

&#34;项目7&#34;,&#34;项目3&#34;,&#34;项目1&#34;,

我选择它的顺序和不喜欢

&#34;项目1&#34;,&#34;项目3&#34;,&#34;项目7&#34;,

怎么做呢

1 个答案:

答案 0 :(得分:0)

首先,您需要每次检查字符串中是否存在元素,否则可以向tmp string添加新值; 结果是:

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String tmp = Sort(parent.getItemAtPosition(position).toString());
                Toast.makeText(getContext(),String.valueOf(tmp),Toast.LENGTH_SHORT).show();
            }
        });
private String Sort(String tmp){

        if (order.contains(tmp)){
            Log.d("contain","contain");
            order = order.replace(","+tmp,"");
        }else if (order.length() == 0){
            order +=  tmp;
        }else {
            order +=  ","+tmp;
        }
        return order;
    }