1

可能重复:
未调用 setOnItemClickListener

setOnItemClickListener 没有响应我的基本适配器。此尝试试图在 baseadapter 的 getView 中处理侦听器。

我的适配器:

import java.io.Serializable;
import java.util.ArrayList;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public  class ModuleAdapter extends BaseAdapter implements Serializable, OnClickListener{
    private static final String TAG = "myAdapter";



    private static final long serialVersionUID = 1L;
    private LayoutInflater modInflater;

    static class ViewHolder{
        TextView moduleCode;
        TextView firstLetter;
        TextView day;
        TextView startTime;
        TextView location;

    }


//  insert holding arrays
    private ArrayList<String> moduleCodeItems = new ArrayList<String>();
    private ArrayList<String> module_name = new ArrayList<String>();
    private ArrayList<String> moduleType = new ArrayList<String>();
    private ArrayList<String> weekDay = new ArrayList<String>();
    private ArrayList<String> classTime = new ArrayList<String>();
    private ArrayList<String> classLocation = new ArrayList<String>();
    private ArrayList<String> commentsField = new ArrayList<String>();

//  setter for the array lists
    public void setModules(String modCode, String modName, String modT, String weekD, String classT, String classL, String commentsF){
        moduleCodeItems.add(modCode);
        module_name.add(modName);
        moduleType.add(modT);
        weekDay.add(weekD);
        classTime.add(classT);
        classLocation.add(classL);
        commentsField.add(commentsF);
//      Log.v(TAG, moduleCodeItems.get(0));
    }

//  getters for the module array list items
    public ArrayList<String> getModuleCodeItems(){
        return moduleCodeItems;
    }

    public ArrayList<String> getModuleNames(){
        return module_name;
    }

    public ArrayList<String> getModuleTypes(){
        return moduleType;
    }

    public ArrayList<String> getWeekDays(){
        return weekDay;
    }

    public ArrayList<String> getClassTimes(){
        return classTime;
    }

    public ArrayList<String> getClassLocations(){
        return classLocation;
    }

    public ArrayList<String> getComments(){
        return commentsField;
    }
//  end of getter methods


//  setter for module array list items
    @SuppressWarnings("unchecked")
    public void setModuleCodeItemsArrayList(Object modCodeArray){
        moduleCodeItems = (ArrayList<String>) modCodeArray;
    }

    @SuppressWarnings("unchecked")
    public void setModuleNameArrayList(Object nameArray){
        module_name = (ArrayList<String>) nameArray;
    }

    @SuppressWarnings("unchecked")
    public void setModuleTypeArrayList(Object typeArray){
        moduleType = (ArrayList<String>) typeArray;
    }

    @SuppressWarnings("unchecked")
    public void setWeekDayArrayList(Object weekArray){
        weekDay = (ArrayList<String>) weekArray;
    }

    @SuppressWarnings("unchecked")
    public void setClassTimeArrayList(Object classArray){
        classTime = (ArrayList<String>) classArray;
    }

    @SuppressWarnings("unchecked")
    public void setClassLocationArrayList(Object locationArray){
        classLocation = (ArrayList<String>) locationArray;
    }

    @SuppressWarnings("unchecked")
    public void setCommentsFieldArrayList(Object commentsArray){
        commentsField = (ArrayList<String>) commentsArray;
    }

//   constructor
    public ModuleAdapter(Context context){

        modInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
//      determine how many objects there are for displaying
        return moduleCodeItems.size();
    }



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

        ViewHolder holder;

        if(convertView == null){
            convertView = modInflater.inflate(R.layout.row, null);

            holder = new ViewHolder();
            holder.moduleCode = (TextView)convertView.findViewById(R.id.module_code_numberRow);
            holder.firstLetter = (TextView)convertView.findViewById(R.id.firstLetterRow);
            holder.day = (TextView)convertView.findViewById(R.id.dayRow);
            holder.startTime = (TextView)convertView.findViewById(R.id.startTimeRow);
            holder.location = (TextView)convertView.findViewById(R.id.locationRow);


            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }
        holder.moduleCode.setText(moduleCodeItems.get(position));
        holder.firstLetter.setText(moduleType.get(position));
        holder.day.setText(weekDay.get(position));
        holder.startTime.setText(classTime.get(position));
        holder.location.setText(classLocation.get(position));
//      Log.v(TAG,(moduleCodeItems.get(position))); 

        holder.moduleCode.setOnClickListener(new View.OnClickListener() {
               public void onClick(View v){  
                   Log.v(TAG, "clicked"); 
                }
             });




        return convertView;
    }

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

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

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

}
//  end of module adapter

我的活动设置了适配器:

public class MainActivity extends Activity {
    private static final String TAG = "someTag";
//  boolean to check if data has been added to the string arrays
    boolean modulesHaveBeenSet;
//  boolean to check to see if the correct module code has been entered for deletion
    boolean newOutputs;
    public String MODULES_FILE = "modules_file";
    Context context = this;
    File file;

//  identifiers for strings to be passed to the next activity via intents
    public final static String TIME_MESSAGE = "timeMessageForNextActivity";
    public final static String DAY_MESSAGE = "dayMessageForNextActivity";




    private static final int MENU_ADD = Menu.FIRST+1;
    private static final int MENU_REMOVE = Menu.FIRST+2;

    ModuleAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

       ListView lv = (ListView)findViewById(R.id.list);
       adapter = new ModuleAdapter(this);
       lv.setAdapter(adapter);





       file = new File(context.getFilesDir(), MODULES_FILE);

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE,MENU_ADD,Menu.NONE,"add module");
        menu.add(Menu.NONE,MENU_REMOVE,Menu.NONE,"delete module");
        return true;


    }



//    forces menu to display when the application launches
//    taken from stack overflow
    @Override
    public void onWindowFocusChanged(boolean hasFocusFlag) {
        super.onWindowFocusChanged(hasFocusFlag);       
        if (hasFocusFlag) {
            openOptionsMenu();
        }
    }
//    end of on window focus

    @Override
        public boolean onOptionsItemSelected(MenuItem item) {
           switch (item.getItemId()) {
        case MENU_ADD:
            add();
            break;
        case MENU_REMOVE:
            remove();
        default:
            break;
        }

            return super.onOptionsItemSelected(item);
        }
//    end of on options selected



    private void add(){
        final View addView = getLayoutInflater().inflate(R.layout.add, null);



        new AlertDialog.Builder(this)
        .setTitle("Enter Module Information")
        .setView(addView)
        .setPositiveButton("OK", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int whichButton){

//          add whatever is in the text fields to the array lists
            EditText moduleEdit = (EditText)addView.findViewById(R.id.module_edit);
            EditText nameEdit = (EditText)addView.findViewById(R.id.module_name_edit);
            EditText typeEdit = (EditText)addView.findViewById(R.id.module_type_edit);
            EditText dayEdit = (EditText)addView.findViewById(R.id.week_day_edit);
            EditText timeEdit =(EditText)addView.findViewById(R.id.time_edit);
            EditText locationEdit = (EditText)addView.findViewById(R.id.location_edit);
            EditText commentsEdit = (EditText)addView.findViewById(R.id.comments_edit);

            try {
                adapter.setModules(moduleEdit.getText().toString(),
                                    nameEdit.getText().toString(),
                                    typeEdit.getText().toString().substring(0, 1).toUpperCase(),
                                    dayEdit.getText().toString().substring(0, 2),
                                    timeEdit.getText().toString(),
                                    locationEdit.getText().toString(),
                                    commentsEdit.getText().toString());
                modulesHaveBeenSet = true;

//          tell the adapter to refresh itself 
                adapter.notifyDataSetChanged();
            } catch (StringIndexOutOfBoundsException e) {
//              recall add method if all edit fields not used
                add();
            }
//              end of try catch
            }
        }).setNegativeButton("Cancel", null).show();



    }
//  end of add  

    public void remove(){
        final View removeView = getLayoutInflater().inflate(R.layout.remove, null);



        new AlertDialog.Builder(this)
        .setTitle("Enter Module to Delete")
        .setView(removeView)
        .setPositiveButton("OK", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int whichButton){
//          get whatever module code was entered in edit text
                EditText removeModCode = (EditText)removeView.findViewById(R.id.remove_mod_code_edit);
                String rm = removeModCode.getText().toString();

                int lengtOfModCodeArrayList = adapter.getModuleCodeItems().size();
                Log.v(TAG,"" + lengtOfModCodeArrayList);
                for(int i =0; i< lengtOfModCodeArrayList; i++){

                    if(adapter.getModuleCodeItems().get(i).equals(rm)){
                        adapter.getModuleCodeItems().remove(i);
                        adapter.getModuleNames().remove(i);
                        adapter.getModuleTypes().remove(i);
                        adapter.getWeekDays().remove(i);
                        adapter.getClassTimes().remove(i);
                        adapter.getClassLocations().remove(i);
                        adapter.getComments().remove(i);
                        Log.v(TAG,"" + lengtOfModCodeArrayList);
                        newOutputs = true;
                    }
//                  if
                }
//              for

//              delete the file and recreate
                boolean deleted = context.deleteFile(MODULES_FILE);
                if(deleted){
                Log.v(TAG, "file deleted");
                }
                file = new File(context.getFilesDir(), MODULES_FILE);

//              update file
                try {

                    ObjectOutputStream moduleOutputs = new ObjectOutputStream(new FileOutputStream(file));
                    moduleOutputs.writeObject(adapter.getModuleCodeItems());
                    moduleOutputs.writeObject(adapter.getModuleNames());
                    moduleOutputs.writeObject(adapter.getModuleTypes());
                    moduleOutputs.writeObject(adapter.getWeekDays());
                    moduleOutputs.writeObject(adapter.getClassTimes());
                    moduleOutputs.writeObject(adapter.getClassLocations());
                    moduleOutputs.writeObject(adapter.getComments());

                    moduleOutputs.flush();
                    moduleOutputs.close();

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
//              update adapter
                adapter.notifyDataSetChanged();

//              raise toast message confirming module removal
                if(newOutputs){
                Context apContext = getApplicationContext();
                CharSequence text = "module " + rm + " deleted";
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(apContext, text, duration);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();}
                else{
                    Context apContext = getApplicationContext();
                    CharSequence text = "module does not exist";
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(apContext, text, duration);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }

            }
        }).setNegativeButton("Cancel", null).show();


    }
//    end of remove




    @Override
        protected void onPause() {
            // TODO Auto-generated method stub
            super.onPause();
            Log.v(TAG, "on pause called");
            if(modulesHaveBeenSet){

                try {
                    ObjectOutputStream moduleOutputs = new ObjectOutputStream(new FileOutputStream(file));
                    moduleOutputs.writeObject(adapter.getModuleCodeItems());
                    moduleOutputs.writeObject(adapter.getModuleNames());
                    moduleOutputs.writeObject(adapter.getModuleTypes());
                    moduleOutputs.writeObject(adapter.getWeekDays());
                    moduleOutputs.writeObject(adapter.getClassTimes());
                    moduleOutputs.writeObject(adapter.getClassLocations());
                    moduleOutputs.writeObject(adapter.getComments());

                    moduleOutputs.flush();
                    moduleOutputs.close();

                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
//          end if
        }
//    end on pause



    @Override
        protected void onResume() {
            // TODO Auto-generated method stub
            super.onResume();
            Log.v(TAG, "on resume called");

            try {
                ObjectInputStream moduleInputs = new ObjectInputStream(new FileInputStream(file));
                adapter.setModuleCodeItemsArrayList(moduleInputs.readObject());
                adapter.setModuleNameArrayList(moduleInputs.readObject());
                adapter.setModuleTypeArrayList(moduleInputs.readObject());
                adapter.setWeekDayArrayList(moduleInputs.readObject());
                adapter.setClassTimeArrayList(moduleInputs.readObject());
                adapter.setClassLocationArrayList(moduleInputs.readObject());
                adapter.setCommentsFieldArrayList(moduleInputs.readObject());
                adapter.notifyDataSetChanged();

            } catch (StreamCorruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



        }
4

0 回答 0