2017-07-18 192 views
0

我正在製作一個程序,將一個Spinner包含在片段中而不是活動中。我研究了爲什麼這可能會崩潰,但無濟於事。我最初的擔心是.getView()。findViewById(),但現在我不太確定這是問題所在,因爲。這是代碼。Spinner片段不斷崩潰

public class Add extends Fragment { 


public Add() { 
    // Required empty public constructor 
} 

ArrayList<String> ingredients = new ArrayList<>(); 
SpinnerDialog spinnerDialog; 
Button add; 


@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 


    add = (Button) getView().findViewById(R.id.add); 
    add.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 

      spinnerDialog.showSpinerDialog(); 

     } 

    }); 
    // Inflate the layout for this fragment 

    return inflater.inflate(R.layout.fragment_add, container, false); 

} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    spinnerDialog = new SpinnerDialog(getActivity(), ingredients, "Select An Ingredient"); 
    spinnerDialog.bindOnSpinerListener(new OnSpinerItemClick() { 
     @Override 
     public void onClick(String Ingredient, int i) { 

      Toast.makeText(Add.super.getContext(), "Selected ", Toast.LENGTH_SHORT).show(); 

     } 
    }); 

回答

1

沒有看到堆棧跟蹤我不能肯定地說,但我懷疑這條線崩潰:

add = (Button) getView().findViewById(R.id.add); 

這是因爲getView()將返回onCreateView()返回的View實例...但你目前裏面的onCreateView(),所以getView()將返回null

你可以按照如下方式重新編寫你的onCreateView(),它應該可以工作。

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState) { 

    View root = inflater.inflate(R.layout.fragment_add, container, false); 
    add = (Button) root.findViewById(R.id.add); 
    add.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      spinnerDialog.showSpinerDialog(); 
     } 
    }); 

    return root; 
}