启动新片段时应用程序崩溃

时间:2016-01-22 15:37:24

标签: android android-fragments android-spinner

我是Android开发人员的新手,当我尝试在点击我的按钮时创建一个新片段时,我的应用程序崩溃,该按钮具有名为“EnterNameOnClick()”的“onClick” 我怀疑MainActivity的以下代码可能是问题......

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void EnterNameOnClick(){
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        EnterName_Fragment enterName_fragment = new EnterName_Fragment();
        fragmentTransaction.add(android.R.id.content, enterName_fragment);
        fragmentTransaction.commit();
    }
}

public class EnterName_Fragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.new_user_fragment, container, false);
        Spinner spinner = (Spinner) view.findViewById(R.id.movie_spinner);

        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(), R.array.planets_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinner.setAdapter(adapter);

        return view;
    }
}

当我编写fragmentTransaction.add(android.R.id.content,enterName_fragment)时,我想知道“android.R.id.content”是否错误?我应该用这个字段来填充这个字段?

1 个答案:

答案 0 :(得分:0)

也许这是因为在xml中使用android:onclick。使用onClickListener

在Java中尝试onClick
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {

    public void EnterNameOnClick(View v) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        EnterName_Fragment enterName_fragment = new EnterName_Fragment();
        fragmentTransaction.add(android.R.id.content, enterName_fragment);
        fragmentTransaction.commit();
    }
});

发布logcat有助于我们提供更好的解决方案。试试吧,让我知道。