Android ListView 实现单选多选

单选布局文件



    

    
    

    

        

        
    


布局文件预览

Android ListView 实现单选多选_第1张图片

MainActivity代码

package com.example.listviewsingle;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ListView lv = (ListView)findViewById(R.id.lv);
		
		final String[] data = {"篮球","足球","棒球","乒乓球","橄榄球","冰球","排球","水球","其他"};
		ArrayAdapter adapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,data);
		
		lv.setOnItemClickListener(new OnItemClickListener() {
			
			@Override
			public void onItemClick(AdapterView parent, View view, int position, long id) {
				TextView like = (TextView)findViewById(R.id.like);
				for (int i = 0; i < data.length; i++) {
					if (position == i) {
						like.setText(data[i]);
						return;
					}
				}
			}
		});

		lv.setAdapter(adapter);
		lv.setSelector(R.drawable.shap);
	}
	
}

效果图

Android ListView 实现单选多选_第2张图片

你可能感兴趣的:(教程,java基础,原创)