2014-07-11 52 views
1

我對Java相當陌生,並且對列表視圖幾乎沒有經驗。我已經能夠使用自定義列表適配器成功添加項目到列表視圖。但是,我現在想要在每個項目被觸摸時執行操作。無法讓OnItemClickListener在Java中爲Android運行

我一直無法獲取OnItemClickListener事件來執行列表項時,我不知道問題出在哪裏。

代碼:

public class FragmentA extends Fragment implements OnItemClickListener{ 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

    View V = inflater.inflate(R.layout.fragment_a, container, false); 

    ListView listView = (ListView)V.findViewById(R.id.list); 


     getData data = getData.getMyData(); 


     CustomList adapter = new 
      CustomList(getActivity(), data.Headline.toArray(new String[data.Headline.size()]), data.Description.toArray(new String[data.Description.size()]), data.imageId.toArray(new Integer[data.imageId.size()]));  
     listView.setAdapter(adapter); 

    return V; 

} 

public void onItemClickListener(AdapterView<?> parent, View view, int position, long id) 
{ 
    Log.e("CLICKED","CLICKED"); 
} 
} 

此外,如果有幫助,這裏是代碼的自定義適配器類:

public class CustomList extends ArrayAdapter<String>{ 

private final Activity context; 
private final String[] titleId; 
private final String[] descriptionId; 
private final Integer[] pictureid; 

public CustomList(Activity context, 
String[] Headline, String[] Description, Integer[] imageId) { 
super(context, R.layout.single_row, Headline); 
this.context = context; 
this.titleId = Headline; 
this.descriptionId = Description; 
this.pictureid = imageId; 

} 
@Override 
public View getView(int position, View view, ViewGroup parent) { 
LayoutInflater inflater = context.getLayoutInflater(); 
View rowView= inflater.inflate(R.layout.single_row, null, true); 

TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle); 
TextView txtDescription = (TextView) rowView.findViewById(R.id.tvDescription); 
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon); 

txtTitle.setText(titleId[position]); 
txtDescription.setText(descriptionId[position]); 
imageView.setImageResource(pictureid[position]); 
return rowView; 
} 

} 
+1

listView.setOnItemClickListener(本);剛剛在setAdapter()後 – zgc7009

+0

謝謝,我添加後,我被提示添加未實現的方法,這是OnItemClick而不是OnItemClickListener。 – jamesgates1

回答

0

您必須使用listView.setOnItemClickListener將回調鏈接到視圖。

你可以做如下:

listView.setOnItemClickListener(new OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> adapter, View view,int pos, long id) { 
     //Your code here 
    } 
}); 

但是,你的情況,作爲活動已經實現OnItemClickListener(),你可以簡單地說:

listView.setOnItemClickListener(this); 
0

將監聽到你的ListView:

listView.setOnItemClickListener(new OnItemClickListener() { 
    @Override 
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
     Log.e("CLICKED","CLICKED"); 
    } 
});