2017-02-09 88 views
0

在我的程序中,我有一個動態添加自定義項目的ListView的片段。這些項目每個都有2個按鈕,這些按鈕應該具有某種功能(如從列表中刪除特定項目)。我想爲他們設置一個OnClickListener,在我的Fragment類中調用一個函數。onClickListener自定義ListView項目與多個按鈕

簡單的xml onClick屬性找不到函數,當我嘗試在onCreateView()方法內添加onClickListener(就像靜態按鈕的Listeners一樣)。但是當片段被創建時,會調用NullPointerException,因爲引用的Button不是Fragment(?)的一部分。

我如何按一個動態添加按鈕(或複選框)之後調用函數從我的片段?

+0

一個項目?不工作點擊? – marlonpya

回答

0

如果您張貼一些代碼

在我的代碼我有類似的東西,這是比較容易的,我有一個列表視圖用數組適配器,並在一些行我有一個ImageButton的一個funtion。

我解決了我的問題,使用類來處理適配器,並且將函數應用於Button。

MAIN_CLASS代碼:

ListViewResources listViewResources = new ListViewResources(this, resourcesName); 
listView = (ListView) popupView.findViewById(R.id.listView1); 
listView.setAdapter(listViewResources); 

ListViewResouces_Class:有兩個按鈕在列表視圖

public class ListViewResources extends ArrayAdapter<String>{ 

Activity context; 
String[] resourcesName; 


public ListViewResources(Activity context, String[] resourcesName) { 
    super(context, R.layout.popup_listitem_resources, resourcesName); 

    this.context = context; 
    this.resourcesName = resourcesName; 

} 

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

    LayoutInflater inflater = context.getLayoutInflater(); 
    View rowView = inflater.inflate(R.layout.popup_listitem_resources, null, true); 

    TextView resourceName = (TextView)rowView.findViewById(R.id.textViewResourceName); 
    ImageView openResource = (ImageView)rowView.findViewById(R.id.buttonOpenResource); 

    openResource.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      //code for happen on Button Click 
     } 
    }); 

    resourceName.setText(resourcesName[position]); 

    return rowView; 
} 
相關問題