web-dev-qa-db-fra.com

Android Élément de ligne personnalisé pour ListView

J'ai un ListView qui devrait avoir la disposition suivante dans ses lignes:

HEADER
Text

HEADER devrait être statique mais le Text change toutes les quelques secondes.

Je l'ai implémenté en remplissant un String[] array, passez-le à un ArrayAdapter et définissez-le chaque fois que les données changent:

data_array = populateString();
adapter = new ArrayAdapter<String>(this, Android.R.layout.simple_list_item_1, Android.R.id.text1,  data_array);
listView.setAdapter(adapter);

Mon problème est que je ne sais pas comment afficher les données dans le format ci-dessus.

Merci d'avance.

73
pteixeira

Ajouter ce fichier row.xml à votre dossier de disposition

<?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="match_parent"
    Android:orientation="vertical" >

<TextView Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:text="Header"/>

<TextView 
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:id="@+id/text"/>


</LinearLayout>

faire votre mise en page principale XML comme cela

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:layout_width="fill_parent"
    Android:layout_height="fill_parent"
    Android:orientation="horizontal" >

    <ListView
        Android:id="@+id/listview"
        Android:layout_width="fill_parent"
        Android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>

Ceci est votre adaptateur

class yourAdapter extends BaseAdapter {

    Context context;
    String[] data;
    private static LayoutInflater inflater = null;

    public yourAdapter(Context context, String[] data) {
        // TODO Auto-generated constructor stub
        this.context = context;
        this.data = data;
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return data[position];
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View vi = convertView;
        if (vi == null)
            vi = inflater.inflate(R.layout.row, null);
        TextView text = (TextView) vi.findViewById(R.id.text);
        text.setText(data[position]);
        return vi;
    }
}

Votre activité Java

public class StackActivity extends Activity {

    ListView listview;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        listview = (ListView) findViewById(R.id.listview);
        listview.setAdapter(new yourAdapter(this, new String[] { "data1",
                "data2" }));
    }
}

les resultats

enter image description here

167
William Kinaan

Utilisez une liste personnalisée.

Vous pouvez également personnaliser l'aspect des lignes en créant un arrière-plan personnalisé. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
 Android:layout_width="fill_parent"
 Android:layout_height="fill_parent"
 Android:orientation="vertical" 
 Android:background="#0095FF"> //background color

<ListView Android:id="@+id/list"
 Android:layout_width="fill_parent"
 Android:layout_height="0dip"
 Android:focusableInTouchMode="false"
 Android:listSelector="@Android:color/transparent"
 Android:layout_weight="2"
 Android:headerDividersEnabled="false"
 Android:footerDividersEnabled="false"
 Android:dividerHeight="8dp" 
 Android:divider="#000000" 
 Android:cacheColorHint="#000000"
Android:drawSelectorOnTop="false">
</ListView>  

Activité principale

Définir populateString () dans MainActivity

 public class MainActivity extends Activity {

   String data_array[];
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
            data_array = populateString(); 
    ListView ll = (ListView) findViewById(R.id.list);
    CustomAdapter cus = new CustomAdapter();
    ll.setAdapter(cus);
}

class CustomAdapter extends BaseAdapter
{
    LayoutInflater mInflater;


    public CustomAdapter()
    {
        mInflater = (LayoutInflater) MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return data_array.length;//listview item count. 
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position; 
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder vh;
        vh= new ViewHolder();

        if(convertView==null )
         {
            convertView=mInflater.inflate(R.layout.row, parent,false);
                    //inflate custom layour
            vh.tv2= (TextView)convertView.findViewById(R.id.textView2);

         }
        else
        {
         convertView.setTag(vh);
        }
               //vh.tv2.setText("Position = "+position);
            vh.tv2.setText(data_array[position]);   
                           //set text of second textview based on position

        return convertView;
    }

 class ViewHolder
 {
    TextView tv1,tv2;
 }

   }  
}

row.xml. Mise en page personnalisée pour chaque ligne.

<?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="match_parent"
 Android:orientation="vertical" >

 <TextView
    Android:id="@+id/textView1"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_gravity="center"
    Android:text="Header" />

 <TextView
    Android:id="@+id/textView2"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:layout_gravity="center"
    Android:text="TextView" />

 </LinearLayout>

Gonfler une mise en page personnalisée. Utilisez un support de vue pour un défilement régulier et des performances.

http://developer.Android.com/training/improving-layouts/smooth-scrolling.html

http://www.youtube.com/watch?v=wDBM6wVEO7 . La discussion porte sur les performances de listview par les développeurs de Android.

enter image description here

9
Raghunandan

créer un fichier de présentation de ressources list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
          Android:orientation="vertical"
          Android:layout_width="match_parent"
          Android:layout_height="wrap_content">
<TextView
        Android:id="@+id/header_text"
        Android:layout_height="0dp"
        Android:layout_width="fill_parent"
        Android:layout_weight="1"
        Android:text="Header"
        />
<TextView
        Android:id="@+id/item_text"
        Android:layout_height="0dp"
        Android:layout_width="fill_parent"
        Android:layout_weight="1"
        Android:text="dynamic text"
        />
</LinearLayout>

et initialiser l'adaptateur comme celui-ci

adapter = new ArrayAdapter<String>(this, R.layout.list_item,R.id.item_text,data_array);
5
Akhil

Étape 1: Créer un fichier XML

 <?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="match_parent"
        Android:orientation="vertical">


        <ListView
            Android:id="@+id/lvItems"
            Android:layout_width="match_parent"
            Android:layout_height="match_parent"
            />
    </LinearLayout>

Étape 2: Studnet.Java

package com.scancode.acutesoft.telephonymanagerapp;


public class Student
{
    String email,phone,address;

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

étape 3: MainActivity.Java

 package com.scancode.acutesoft.telephonymanagerapp;

    import Android.app.Activity;
    import Android.os.Bundle;
    import Android.widget.ListView;

    import Java.util.ArrayList;

    public class MainActivity extends Activity  {

        ListView lvItems;
        ArrayList<Student> studentArrayList ;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            lvItems = (ListView) findViewById(R.id.lvItems);
            studentArrayList = new ArrayList<Student>();
            dataSaving();
            CustomAdapter adapter = new CustomAdapter(MainActivity.this,studentArrayList);
            lvItems.setAdapter(adapter);
        }

        private void dataSaving() {

            Student student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Hyderabad");
            studentArrayList.add(student);


            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);

            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);

            student = new Student();
            student.setEmail("[email protected]");
            student.setPhone("1234567890");
            student.setAddress("Banglore");
            studentArrayList.add(student);
        }


    }

étape 4: CustomAdapter.Java

  package com.scancode.acutesoft.telephonymanagerapp;

    import Android.content.Context;
    import Android.view.LayoutInflater;
    import Android.view.View;
    import Android.view.ViewGroup;
    import Android.widget.BaseAdapter;
    import Android.widget.TextView;

    import Java.util.ArrayList;


    public class CustomAdapter extends BaseAdapter
    {
        ArrayList<Student> studentList;
        Context mContext;


        public CustomAdapter(Context context, ArrayList<Student> studentArrayList) {
            this.mContext = context;
            this.studentList = studentArrayList;

        }

        @Override
        public int getCount() {
            return studentList.size();
        }
        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            Student student = studentList.get(position);
            convertView = LayoutInflater.from(mContext).inflate(R.layout.student_row,null);

            TextView tvStudEmail = (TextView) convertView.findViewById(R.id.tvStudEmail);
            TextView tvStudPhone = (TextView) convertView.findViewById(R.id.tvStudPhone);
            TextView tvStudAddress = (TextView) convertView.findViewById(R.id.tvStudAddress);

            tvStudEmail.setText(student.getEmail());
            tvStudPhone.setText(student.getPhone());
            tvStudAddress.setText(student.getAddress());


            return convertView;
        }
    }
2
Manikanta Reddy

vous pouvez suivre BaseAdapter et créer votre fichier personnalisé Xml et le lier avec vous BaseAdpter et le remplir avec Listviewvoir ici besoin de changer le fichier xml comme Require.

1