实现可以多选的Android ListView列表
fydxdk
9年前
public class TestActivity extends Activity { /**代码中写布局的View*/ private LinearLayout mParentLinearLayout; /**标题TextView*/ private TextView mTitleTv; /**展示数据的ListView*/ private ListView mListView; /**自定义的数据*/ private String[] mStrArray; /**ListView的数据适配器*/ private ArrayAdapter<String> arrayAdapter; /**定义一StringBuffer*/ private StringBuffer mBuffer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initViews(); initListeners(); } private void initListeners() { mListView.setOnItemSelectedListener(mLvOnItemSelectedListener); mListView.setOnItemClickListener(mLvOnItemClickListener); } private void initViews() { /**初始化mParentLinearLayout*/ mParentLinearLayout = new LinearLayout(TestActivity.this); /**设置布局宽高*/ LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); /**布局排列方式*/ mParentLinearLayout.setOrientation(LinearLayout.VERTICAL); /**背景*/ mParentLinearLayout.setBackgroundColor(Color.parseColor("#F0F0F0")); mTitleTv = new TextView(TestActivity.this); mTitleTv.setLayoutParams(mLayoutParams); mTitleTv.setText("请选择列表数据!"); mTitleTv.setTextColor(Color.BLACK); /**往布局中添加TextView*/ mParentLinearLayout.addView(mTitleTv); mListView = new ListView(TestActivity.this); mListView.setLayoutParams(mLayoutParams); mListView.setBackgroundColor(Color.LTGRAY); mBuffer = new StringBuffer(); mStrArray = new String[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; arrayAdapter = new ArrayAdapter<String>(TestActivity.this, android.R.layout.simple_list_item_multiple_choice, mStrArray); /**设置ListView的选择模式*/ mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); mListView.setAdapter(arrayAdapter); /**往布局中添加ListView*/ mParentLinearLayout.addView(mListView); setContentView(mParentLinearLayout); } private OnItemSelectedListener mLvOnItemSelectedListener = new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { /**选中后的操作*/ mBuffer.append(arg0.getItemAtPosition(arg2).toString() + "-"); mTitleTv.setText(mBuffer.toString()); } public void onNothingSelected(AdapterView<?> arg0) { } }; OnItemClickListener mLvOnItemClickListener = new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { /**点击后的操作*/ mBuffer.append(arg0.getItemAtPosition(arg2).toString() + ""); mTitleTv.setText(mBuffer.toString()); /**还可以判断,如果已经选中,点击的话应该表示不选中*/ } }; }