0
我使用ListView和SimpleCursorAdapter以標準方式顯示項目列表。在每個列表行中,我有一個Button視圖,以便可以觸發刪除事件。但是,當我的應用程序啓動時,我不斷收到NPE,我無法弄清楚原因。我確定我忽略了一些簡單的東西,但我不知道在哪裏。以下是我有:需要幫助從我的佈局中的按鈕訪問我的活動中的方法。繼續獲得NPE
MyActivity.java
public class MyActivity extends Fragment {
private View rootView;
private SwipeRefresh mySwipeRefresh;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootView = inflater.inflate(R.layout.my_layout, container, false);
mySwipeRefresh = (SwipeRefresh)rootView.findViewById(R.id.my_swipe_refresh);
}
@Override
public void onViewCreated(View rootView, Bundle savedInstanceState){
super.onViewCreated(rootView savedInstanceState);
drawTheList();
}
public void drawTheList(){
DatabaseHelpler dbHelper = new DatabaseHelper(getActivity());
Cursor cursor = dbHelper.getDataCursor();
String[] fromColumns = {"data01","data02","data03","data04"};
int[] toViews = {R.id.view01, R.id.view02, R.id.view03, R.id.view04};
SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(getContext(), R.layout.line_of_data, cursor, fromColumns, toViews, 0);
ListView listView = (ListView)rootView.findViewById(R.id.data_rows);
listView.setAdapter(simpleCursorAdapter);
dbHelper.close;
Button deleteButton = (Button)listView.findViewById(R.id.remove_item);
deleteButton.setOnClickListener(deleteButtonListener);
}
View.OnClickListener deleteButtonListener = new View.OnClickListener(){
@Override
public void onClick(View view){
Toast.makeText(rootView.getContext(), "message", Toast.LENGTH_LONG).show();
}
};
}
my_layout.xml
<LinearLayout>
<android.support.v4.widget.SwipeRefreshLayout>
<ListView android:id="@+id/data_rows" />
</android.support.v4.widget.SwipeRefreshLayout>
</LinearLayout>
line_of_data
<LinearLayout android:orientation="horizontal">
<TextView android:id="@+id/view01" />
<TextView android:id="@+id/view02" />
<TextView android:id="@+id/view03" />
<TextView android:id="@+id/view04" />
<LinearLayout android:orientation="horizontal">
<ImageView />
<Button android:id="@+id/remove_item" />
</LinearLayout>
</LinearLayout>
NPE來自線路deleteButton.setOnClickListener(deleteButtonListener);
。當我評論這一行時,應用程序啓動就好了。
我試圖用我的XML簡單android:onClick="deleteMethod"
且在我的活動deleteMethod,但該方法是從來沒有可供按鈕(AndroidStudio就不會顯示該方法,當我用Ctrl +空格鍵)
什麼我錯過了嗎?
感謝
好吧,我這樣做,它的工作原理... 有點。現在view01到view04中的所有信息都消失了。此外,我不得不改變'Button yourButton =(Button)findViewById(R.id.remove_item);'to'Button yourButton =(Button)view.findViewById(R.id.remove_item);'。 – Brian
您需要綁定它們並在'bindView'方法中調用settext .. – rafsanahmad007
對於我想要顯示的每個元素?我不需要用''來做這件事,因爲它顯示正確。 –
Brian