Android small function (1): realize single-selection function in ListView

https://www.jianshu.com/p/6af0a7a59756

Relying on the basis of previous Java, the company has the opportunity to learn while developing Android. This series hopes to spur me to summarize and learn some practical small functions in the project, and also deepen my understanding of Android development.
Entering the topic, I put this small single-selection function in a small scene, which is to choose my favorite mobile phone brand. The effect after completion is as follows:

Single choice.jpg

The tool used in the project is Google
’s son Android Studio Let's coding:
From the picture we can see that we need a ListView. Then there is a custom Adapter for ListView.
The code is as follows, first is the layout file:
activity_main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/id_myList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:choiceMode="singleChoice"
        android:cacheColorHint="@android:color/transparent"
        android:listSelector="@android:color/transparent">
    </ListView>
</RelativeLayout>

We continue, with the ListView we initialize the view and corresponding data. The initialized data is very simple, there is only one String type variable:

 

public class Brand {    
   private String bandname;    
   public Brand(String bandname){        
       this.bandname = bandname;    
   }    
   public String getBandname() { 
       return bandname;    
   }    
   public void setBandname(String bandname) { 
       this.bandname = bandname;                             
   }
}

The next step is to initialize the view and Adapter data in MainAcitivity:

 

public class MainActivity extends AppCompatActivity {


    private ListView mListView; //首页的ListView
    private List<Brand> namesList; //用于装载数据的集合
    private int selectPosition = -1;//用于记录用户选择的变量
    private Brand selectBrand; //用户选择的品牌

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initDatas();
    }

    private void initView(){
        mListView = (ListView)findViewById(R.id.id_myList);
    }

    private void initDatas(){
        //初始化ListView适配器的数据
        namesList = new ArrayList<>();
        Brand brand0 = new Brand("apple");
        Brand brand1 = new Brand("sony");
        Brand brand2 = new Brand("xiaomi");
        Brand brand3 = new Brand("oppo");
        Brand brand4 = new Brand("meizu");
        Brand brand5 = new Brand("smartisan");
        Brand brand6 = new Brand("vivo");
        Brand brand7 = new Brand("samsung");
        Brand brand8 = new Brand("letv");
        Brand brand9 = new Brand("nubia");
        Brand brand10 = new Brand("lg");
        Brand brand11 = new Brand("qiku");
        Brand brand12 = new Brand("huawei");
        namesList.add(brand0);
        namesList.add(brand1);
        namesList.add(brand2);
        namesList.add(brand3);
        namesList.add(brand4);
        namesList.add(brand5);
        namesList.add(brand6);
        namesList.add(brand7);
        namesList.add(brand8);
        namesList.add(brand9);
        namesList.add(brand10);
        namesList.add(brand11);
        final MyAdapter myAdapter = new MyAdapter(this,namesList);
        mListView.setAdapter(myAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //获取选中的参数
                selectPosition = position;
                myAdapter.notifyDataSetChanged();
                selectBrand = namesList.get(position);
                Toast.makeText(MainActivity.this,"您选中的手机品牌是:"+selectBrand.getBandname(),Toast.LENGTH_SHORT).show();
            }
        });
    }

    public class MyAdapter extends BaseAdapter{
        Context context;
        List<Brand> brandsList;
        LayoutInflater mInflater;
        public MyAdapter(Context context,List<Brand> mList){
            this.context = context;
            this.brandsList = mList;
            mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return brandsList.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            if(convertView == null){
                convertView = mInflater.inflate(R.layout.adapter_item,parent,false);
                viewHolder = new ViewHolder();
                viewHolder.name = (TextView)convertView.findViewById(R.id.id_name);
                viewHolder.select = (RadioButton)convertView.findViewById(R.id.id_select);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder)convertView.getTag();
            }
            viewHolder.name.setText(brandsList.get(position).getBandname());
            if(selectPosition == position){
                viewHolder.select.setChecked(true);
            }
            else{
                viewHolder.select.setChecked(false);
            }
            return convertView;
        }
    }
    public class ViewHolder{
        TextView name;
        RadioButton select;
    }
}

Finally, the layout of the Adapter

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="100dp">
    <RadioButton
        android:id="@+id/id_select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:button="@null"
        android:layout_marginLeft="10dp"
        android:background="@drawable/radio"
        android:checked="false"
        android:clickable="false"
        android:focusable="false"
        android:focusableInTouchMode="false"/>
    <TextView
        android:id="@+id/id_name"
        android:layout_marginLeft="10dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16dp"
        android:layout_gravity="center"
        android:text="姓名"/>
</LinearLayout>

Here are a few points to explain:
1. In the future, to prevent the RadioButton from being unselected after the ListView item is clicked, set the clickable attribute to false, and set the ListView android:choiceMode="singleChoice"to be easy to understand according to the name, which is the single- select mode;
2. Pay attention here is convertView = mInflater.inflate(R.layout.adapter_item,parent,false);the convertView = mInflater.inflate(R.layout.adapter_item,null);difference, to set ListView row height will be initialized in accordance with the former convertView.
3. Please refer to the source code for the style and image resources of RadioButton.

https://github.com/gangdou91up/MultipleApplication.git



Author: Gang bean
link: https: //www.jianshu.com/p/6af0a7a59756
Source: Jane books
are copyrighted by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/az44yao/article/details/112611133
Recommended