定制适配器列表视图

时间:2012-06-27 10:20:32

标签: android arraylist adapter

我的项目需要一些帮助。我已经创建了一个自定义适配器,因为我希望我的列表视图显示5个textview,而不是我迄今为止设法做的那个。这是我的CustomAdapterPn活动:

public class CustomAdapterPn extends BaseAdapter {
private static ArrayList<Poniedzialek> searchPnArrayList;

 private LayoutInflater mInflater;

 public CustomAdapterPn(final Context context, final ArrayList<Poniedzialek> results) {
  searchPnArrayList = results;
  mInflater = LayoutInflater.from(context);
 }

 public int getCount() {
  return searchPnArrayList.size();
 }

 public Object getItem(int position) {
  return searchPnArrayList.get(position);
 }

 public long getItemId(int position) {
  return position;
 }
 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  ViewHolder holder;
  if (convertView == null) {
   convertView = mInflater.inflate(R.layout.entry, null);
   holder = new ViewHolder();
   holder.txtSession = (TextView) convertView.findViewById(R.id.textSession);
   holder.txtName = (TextView) convertView.findViewById(R.id.textName);
   holder.txtStart = (TextView) convertView.findViewById(R.id.textStartTime);
   holder.txtEnd = (TextView) convertView.findViewById(R.id.textEndTime);
   holder.txtRoom = (TextView) convertView.findViewById(R.id.textRoom);

   convertView.setTag(holder);
  } else {
   holder = (ViewHolder) convertView.getTag();
  }

  holder.txtSession.setText(searchPnArrayList.get(position).getTypeOfSession());
  holder.txtName.setText(searchPnArrayList.get(position).getName());
  holder.txtStart.setText(searchPnArrayList.get(position).getStartTime());
  holder.txtEnd.setText(searchPnArrayList.get(position).getEndTime());
  holder.txtRoom.setText(searchPnArrayList.get(position).getRoom());

  return convertView;
 }

 static class ViewHolder {

  TextView txtSession;
  TextView txtName;
  TextView txtStart;
  TextView txtEnd;
  TextView txtRoom;
 }

}

这是我希望使用此CustomAdapter的Activity。请注意,我使用ArrayAdapter来显示列表项 - 我还没有修改代码,因为我无法正确地管理这个自定义适配器(我试图,但没有任何效果)。我是一个新手,所以我很难得到这个,虽然我正在阅读大量的教程。

    public class PoniedzialekActivity extends Activity implements OnClickListener, OnItemClickListener{ // z ListActivity na Activity

    private Button butPnAdd;
    private Button butPnDelete;
    private ListView list_Pn;

    private static final int DIALOG_ALERT = 10;

        // We need some kind of Adapter to made the connection between ListView UI component and SQLite data set.
        private ListAdapter pn_list_adapter;
        // We need this while we read the query using Cursor and pass data
        private ArrayList<Poniedzialek> pn_list;    

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_poniedzialek);

        butPnAdd = (Button) findViewById(R.id.butPnAdd);
        butPnAdd.setOnClickListener(this);

        butPnDelete = (Button) findViewById(R.id.butPnDel);
        butPnDelete.setOnClickListener(this);

        // Initialize UI components
        list_Pn = (ListView) findViewById(R.id.listPn);
        list_Pn.setOnItemClickListener(this);

        pn_list = new ArrayList<Poniedzialek>();

        // For the third argument, we need a List that contains Strings.
        //We decided to display undergraduates names on the ListView.
        //Therefore we need to create List that contains undergraduates names
        pn_list_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
        list_Pn.setAdapter(pn_list_adapter);


    }
    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.butPnAdd){
        Intent i = new Intent(PoniedzialekActivity.this,dodawaniePoniedzialek.class);
        startActivity(i);
        }
        if(v.getId()==R.id.butPnDel){
            showDialog(DIALOG_ALERT);
        }
    }
                /**
                 * DIALOG
                 */
                protected Dialog onCreateDialog(int id) {
                    switch (id) {
                    case DIALOG_ALERT:
                        // Create out AlterDialog
                        Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("Czy na pewno chcesz usunac wszystkie wpisy ?");
                        builder.setCancelable(true);
                        builder.setPositiveButton("Tak", new OkOnClickListener());
                        builder.setNegativeButton("Nie", new CancelOnClickListener());
                        AlertDialog dialog = builder.create();
                        dialog.show();
                    }
                    return super.onCreateDialog(id);
                }
                private final class CancelOnClickListener implements
                DialogInterface.OnClickListener {
                    public void onClick(DialogInterface dialog, int which) {
                        // Nic nie robi
                    }
                }
                private final class OkOnClickListener implements
                DialogInterface.OnClickListener {
                    public void onClick(DialogInterface dialog, int which) {            
                        DeletePn();
                        onResume();
                    }
                }
                public void DeletePn(){ 
                    DatabaseHelper openHelperClass = new DatabaseHelper(this);
                    SQLiteDatabase sqliteDatabase = openHelperClass.getWritableDatabase();

                    sqliteDatabase.delete(DatabaseHelper.PN_TABLE, null, null);

                }
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub

    }
        // To create a List that contains undergraduate names, we have to read the SQLite database
        //We are going to do it in the separate method
        public List<String> populateList(){

            // We have to return a List which contains only String values. Lets create a List first
            List<String> pn_string_list = new ArrayList<String>();

            // First we need to make contact with the database we have created using the DbHelper class
            DatabaseHelper openHelperClass = new DatabaseHelper(this);

            // Then we need to get a readable database
            SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();

            // We need a a guy to read the database query. Cursor interface will do it for us
            //(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
            Cursor cursor = sqliteDatabase.query(DatabaseHelper.PN_TABLE, null, null, null, null, null, null);
            // Above given query, read all the columns and fields of the table

            startManagingCursor(cursor);

            // Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
            while (cursor.moveToNext()) {
                // In one loop, cursor read one undergraduate all details
                // Assume, we also need to see all the details of each and every undergraduate
                // What we have to do is in each loop, read all the values, pass them to the POJO class
                //and create a ArrayList of undergraduates

                String session = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_TYPE_OF_SESSION));
                String start = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_START_TIME));
                String end = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_END_TIME));
                String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_NAME));
                String room = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PN_KEY_ROOM));

                // Finish reading one raw, now we have to pass them to the POJO
                Poniedzialek pn = new Poniedzialek();
                pn.setTypeOfSession(session);
                pn.setName(name);
                pn.setStartTime(start);
                pn.setEndTime(end);
                pn.setRoom(room);

                // Przekazujemy pn do arraylist
                pn_list.add(pn);
                // But we need a List of String to display in the ListView also.
                // That is why we create "pn_string_list"
                pn_string_list.add(name);
            }
            // Jezeli Baza Danych nie zostanie zamknieta dostaniemy error
            sqliteDatabase.close();
            return pn_string_list;
        }
        // If you don't write the following code, you wont be able to see what you have just insert to the database
        @SuppressWarnings("unchecked")
        @Override
        protected void onResume() {
            super.onResume();
            pn_list_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());
            list_Pn.setAdapter(pn_list_adapter);
            ((ArrayAdapter<String>) pn_list_adapter).notifyDataSetChanged(); // dodano
            list_Pn.refreshDrawableState(); // dodanoe
            list_Pn.invalidate(); // dodanoe
        }
} // end PoniedzialekActivity

2 个答案:

答案 0 :(得分:1)

为自定义适配器类CustomAdapterPn创建一个对象,并将此自定义适配器对象设置为列表视图。不是阵列适配器。

答案 1 :(得分:0)

查看这些行并根据它进行更改

CustomAdapterPn pn_list_adapter; //change 1

pn_list = new ArrayList<Poniedzialek>();
populateList() // Change 2
pn_list_adapter = new CustomAdapterPn(this,pn_list); // Change 3
list_Pn.setAdapter(pn_list_adapter);

试试这个,让我知道发生了什么......