从片段android启动活动时出错

时间:2017-02-22 01:04:02

标签: android android-layout android-studio android-fragments android-activity

我有MainActivity,其中包含3个片段,我想从MainActivity中的一个片段切换到Activity2,但我的尝试总是失败。当我按下第三个片段中的ok按钮将我连接到Activity2时,我的应用程序崩溃了。我正在研究我在一个教程中找到的代码。先感谢您!

public class ProfileFragment extends Fragment implements View.OnClickListener {

    private TextView tv_name,tv_email,tv_message;
    private SharedPreferences pref;
    private AppCompatButton btn_change_password,btn_logout, btn_ok;
    private EditText et_old_password,et_new_password;
    private AlertDialog dialog;
    private ProgressBar progress;


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

        View view = inflater.inflate(R.layout.fragment_profile,container,false);
        initViews(view);
        return view;

    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        pref = getActivity().getPreferences(0);
        tv_name.setText("Здравей, "+pref.getString(Constants.NAME,"")+"!");
        tv_email.setText(pref.getString(Constants.EMAIL,""));
        btn_ok=(AppCompatButton)view.findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(),activity2.class);
                startActivity(intent);
            }
        });



    }

    private void initViews(View view){

        tv_name = (TextView)view.findViewById(R.id.tv_name);
        tv_email = (TextView)view.findViewById(R.id.tv_email);
        btn_change_password = (AppCompatButton)view.findViewById(R.id.btn_chg_password);
        btn_logout = (AppCompatButton)view.findViewById(R.id.btn_logout);
        btn_ok=(AppCompatButton)view.findViewById(R.id.btn_ok);
        btn_change_password.setOnClickListener(this);
        btn_logout.setOnClickListener(this);


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.btn_chg_password:
                showDialog(); //I deleted this method from the code, it doesnt have a lot in common with my question
                break;
            case R.id.btn_logout:
                logout();
                break;
}

    private void logout() {
        SharedPreferences.Editor editor = pref.edit();
        editor.putBoolean(Constants.IS_LOGGED_IN,false);
        editor.putString(Constants.EMAIL,"");
        editor.putString(Constants.NAME,"");
        editor.putString(Constants.UNIQUE_ID,"");
        editor.apply();
        goToLogin();
    }

    private void goToLogin(){

        Fragment login = new LoginFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.replace(R.id.fragment_frame,login);
        ft.commit();
    }


}

3 个答案:

答案 0 :(得分:0)

您无法在片段中调用方法goToLogin(),您需要在活动中调用包含此片段的内容,因为您的片段不包含布局fragment_frame,它位于您的活性。

如果您想在片段中调用此方法,可以将方法goToLogin()移到yourActivity,然后像这样调用片段:

if(getActivity() instanceOf yourActivity) {
       ((youActivity) getActivity()).goToLogin();
}

答案 1 :(得分:0)

在startActivity()之前添加getActivity作为上下文 还添加了NewTask Flag。

Intent intent = new Intent(getActivity(), activity2.class);
intent.addflags(intent.flag_activity_new_task);
getActivity().startActivity(intent);

答案 2 :(得分:0)

可能会发生错误,因为您没有在AndroidManifest.xml中注册Activity2。

但要从片段活动进行通信,您应该使用MainActivity作为它的门。虽然看起来有点矫枉过正,但它将在未来为更大的项目轻松维护。

您可以使用界面

在您的ProfileFragment中定义并创建一个界面:

public class ProfileFragment extends Fragment implements View.OnClickListener {

    OnProfileListener mCallback;

    // Container Activity must implement this interface
    public interface OnProfileListener {
        public void onProfileButtonOkClicked();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnProfileListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnProfileListener");
        }
    }

    ...
    ...
}

然后在按钮单击方法中调用界面:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    ...
    btn_ok=(AppCompatButton)view.findViewById(R.id.btn_ok);
    btn_ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallback.onProfileButtonOkClicked();
        }
    });
    ...
}

最后,您需要实现MainActivity的接口:

public static class MainActivity extends Activity
        implements ProfileFragment.OnProfileListener{
    ...

    // When button ok in ProfileFragment clicked, this method will be called.
    public void onProfileButtonOkClicked() {
        // we can call the Activity here now.
        Intent intent=new Intent(this, activity2.class);
        startActivity(intent);
    }
}

有关详情,请参阅Communicating with Other Fragments

<强>更新

对于API级别&gt; = 23中已弃用的onAttach(),您可以改为使用以下代码:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnProfileListener) {
        mCallback = (OnProfileListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnProfileListener");
    }
}