Two views in each list item

前端 未结 2 1745
有刺的猬
有刺的猬 2021-01-15 14:35

I\'m trying to show two different views in each element of the list. Both vews are text views, but I want one of them to be enclosed in a square with a different color. I kn

2条回答
  •  孤城傲影
    2021-01-15 15:02

    You can create your own adapter for the list. The adapter is what decides how to display the items in the list.
    Here is an example:

    class MyAdapter extends ArrayAdapter{
            public MyAdapter(Context context, int textViewResourceId, ArrayList objects) {
                super(context, textViewResourceId, objects);
            }
    
            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                if( convertView== null ) convertView = getLayoutInflater().inflate(R.layout.your_layout, null);
    
                TextView myTextView1 = (TextView)convertView.findViewById(R.id.yourFirstTextView);
                myTextView1.setText(getItem(position*2)); //getItem gets the item (String in this case) from the list we specified when creating the adapter.
                //position is the current position of the list, and since each position has two items, we have to multiply the position by 2 to get to the right item-list-position.
                TextView myTextView2 = (TextView)convertView.findViewById(R.id.yourSecondTextView);
                myTextView2.setText(getItem(position*2 +1 ));
                myTextView2.setBackgroundColor(0xFFFF00FF); //Any color. Use setBackgroundResource to use a resource object (drawable etc.)
    
                return convertView;
            }
        }
    

    And you also need the line-layout to contain all the elements you need (this is what will be displayed on each line of the list), let's call it 'thelinelayoutfile.xml' and put it in the layout folder:

    
    
        
        
    
    

    Then when you initialize your list (in your onCreate() method, perhaps?) You call

    //You can create the list anywhere, or use an array.
    //I will create it here, just for the sake of demonstration.
    ArrayList myLines = new ArrayList();
    myLines.add("item1, line1");
    myLines.add("item1, line2");
    myLines.add("item2, line1");
    myLines.add("item2, line2");
    
    //set the list adapter:
    ListView myList = (ListView)findViewById(R.id.whateveryourlistidis);
    myList.setAdapter(new MyAdapter(this, R.layout.thelinelayoutfile, myLines));
    

提交回复
热议问题