0

У меня есть 3 фрагмента в главной операции, и у одной из них есть кнопка, которую я хочу запустить Activity 2. Я создал интерфейс в третьем фрагменте и расширил главную активность с ним , но я не могу понять, почему мое приложение все еще падает. Я потерял 2 дня по этому вопросу, и это заставило меня с ума сойти. Моя активность 2 объявлена ​​в файле манифеста. Пожалуйста помоги!!!Приложение сработает, когда я пытаюсь переключиться с фрагмента на активность

Profile.Fragment:

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; 

    public interface OnProfileListener{ 
     void onProfileButtonOkClicked(); 
    } 

    private OnProfileListener mCallBack; 

    @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) { 
       mCallBack.onProfileButtonOkClicked(); 
      } 
     }); 


    } 

//I have API16 and I cannot run my app with 
//onAttach(Context context) because it is supported by API>=23, 
//but Android deprecated API16, so that is why I use both Activity and Context 

    @SuppressWarnings("deprecation") 
    @Override 
    public void onAttach(Activity activity) { 
     super.onAttach(activity); 
     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) { 
      if (activity instanceof OnProfileListener){ 
      mCallBack = (OnProfileListener) activity; 
     } else { 
      throw new RuntimeException(activity.toString() 
        + " must implement OnProfileListener"); 
     } 
    }} 
    @TargetApi(23) 
    @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"); 
     } 
    } 

... 
    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); 


    } 

    //Here I go to other fragment in Main Activity flawlessly, wish I could manage to go Activity2 with the same ease 

    private void goToLogin(){ 

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

MainActivity.java:

import android.content.Intent; 
import android.content.SharedPreferences; 
import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.support.v4.app.FragmentActivity; 
import android.support.v4.app.FragmentTransaction; 

public class MainActivity extends FragmentActivity implements 
     ProfileFragment.OnProfileListener{ 

    private SharedPreferences pref; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     pref = getPreferences(0); 
     initFragment(); 
     onProfileButtonOkClicked(); 
    } 
    @Override 
    public void onProfileButtonOkClicked() { 

     Intent intent=new Intent(this, Activity2.class); 
     startActivity(intent); 
    } 

    private void initFragment(){ 
     Fragment fragment; 
     if(pref.getBoolean(Constants.IS_LOGGED_IN,false)){ 
      fragment = new ProfileFragment(); 

     }else { 
      fragment = new LoginFragment(); 
     } 
     FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
     ft.replace(R.id.fragment_frame,fragment); 
     ft.commit(); 
    } 
+1

ли вы пост журнал сбоев пожалуйста. –

+0

мое приложение запускается на мобильном устройстве, а затем падает, я не вижу ошибки в журнале событий, он пишет BUILD SUCCESSFUL – Victoria

+0

Итак, ваше приложение падает при запуске? –

ответ

0

Для того, чтобы умысел фрагмента деятельности добавить этот ,,

 public void functionname(View v) 
    { 
     Intent in = new Intent(getActivity(), MainActivity2.class); 
     startActivity(in); 
    } 

здесь, добавьте эту строку в XML-файл этой деятельности, где находится кнопка

андроид: OnClick = «имя_функция»

и "MainActivity2.class" - следующее действие для перемещения.

«Цель состоит в том, чтобы нажать на кнопку, чтобы перейти к mainactivity2.class через это намерение ...

надеюсь, что это будет help..thanks ,,

0

вы не должны начать другую деятельность, когда первая деятельность все еще находится в состоянии создания. Я понятия не имею, почему вы начинаете работу2 до нажатия кнопки. Если вам нужно, вы можете поместить onProfileButonOKClicked() в обработчик onCreated().

+0

Моя цель - запустить Activity2, когда кнопка нажата, и именно по этой причине я добавил onProfileButtonOkClicked(); потому что я думаю, что это что-то вроде OnClickListener – Victoria

Смежные вопросы