2015-11-13 38 views
1

我在一個片段中創建了一個ListView,並使用onStart()方法中名爲Workout的類中的數據填充它。我設置了一個Adapter並且列表顯示正常。我想現在能夠獲取用戶點擊的特定行的值,但無法實現onItemClicked()方法。有誰知道我怎麼能得到這個價值?謝謝。onItemClicked()在片段

public class WorkoutListFragment extends Fragment { 
static interface WorkoutListListener{ 
    void itemClicked(long id); 
} 
private WorkoutListListener listener; 
private ListView workoutList; 
private LayoutInflater inflate; 

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    inflate = inflater; 
    return inflater.inflate(R.layout.fragment_workout_list, container, false); 
} 

@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
    this.listener = (WorkoutListListener)activity; 
} 

@Override//ISSUE IS IN HERE 
public void onStart() { 
    super.onStart(); 
    View view = getView(); 
    String[]names = new String[Workout.workouts.length]; 
    for (int i = 0; i < names.length; i++){ 
     names[i] = Workout.workouts[i].getName(); 
    } 
    if (view!=null){ 
     workoutList = (ListView)view.findViewById(R.id.listView); 
     ArrayAdapter<String>adapter = new ArrayAdapter<String>(inflate.getContext(), 
       android.R.layout.simple_list_item_1,names); 
     workoutList.setAdapter(adapter); 
    } 

    //HOW CAN I NOW GET THE VALUE OF THE ITEM CLICKED? 
    // I TRIED THIS BUT IT'S NOT RECOGNIZED 
    workoutList.setOnClickListener(new onItemClickListener); 
} 

回答

1

使用此:

workoutList.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      // the 'position' argument is the position you are looking for 
    } 
}); 

編輯:

我注意到,你是不是初始化workoutList的ListView。你應該這樣做在OnCreateView方法:

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_workout_list, container, false); 
    workoutList = (ListView) view.findViewById(R.id.workoutListView); // assuming that your listView's id is "@+id/workoutListView" 
    return view; 
}