Spinner Fragment不断崩溃

时间:2017-07-18 01:46:41

标签: java android spinner

我正在制作一个程序,在一个片段而不是一个活动中包含一个Spinner。我已经研究过为什么这可能会崩溃,但无济于事。我最初担心的是.getView()。findViewById(),但现在我不太确定这是问题因为。这是代码。

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 个答案:

答案 0 :(得分:1)

没有看到堆栈跟踪我无法肯定地说,但我怀疑这条线路崩溃了:

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

这是因为getView()会返回View返回的onCreateView()个实例...但您目前 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;
}