启动新的活动会导致应用重新启动

时间:2020-04-02 11:50:36

标签: java android

我创建了一个按钮,它将打开一个新活动,但是当我启动该应用程序并单击该按钮时,该应用程序将立即重新启动,而不会出现任何logcat错误。这是我的代码:

public class amumu extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.amumu, container, false);
}

public void OnClickAmumuRunes(View view){
    Intent GoToRunes = new Intent(view.getContext(), amumurunes.class);
    startActivity(GoToRunes);
}

public void OnClickAmumuBuild(View view){
    Intent GoToRunes = new Intent(view.getContext(), amumubuild.class);
    startActivity(GoToRunes);
}

这是我要打开的代码,但我不能:

public class amumubuild extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.amumubuild, container, false);
}

}

这是一个fragmentclass,其中的tablayout中的第一类是

public class FragmentClass extends AppCompatActivity {
private ViewPager viewPager;
private TabLayout tabLayout;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragments);
    initViews();
    setuppager();

}

private void initViews(){
    viewPager = findViewById(R.id.ViewPager);
    tabLayout = findViewById(R.id.tab);
}

private void setuppager(){
    PagerAdapter pagerAdapter = new SlideAdapter(getSupportFragmentManager());
    viewPager.setAdapter(pagerAdapter);
    tabLayout.setupWithViewPager(viewPager);
}
public void OnClickDisplayToastAmumu(View view) {
    Toast.makeText(this,"Amumu",Toast.LENGTH_SHORT).show();
}

public void OnClickDisplayToastLee(View view) {
    Toast.makeText(this,"Lee Sin",Toast.LENGTH_SHORT).show();
}

public void OnClickDisplayToastPantheon(View view) {
    Toast.makeText(this,"Pantheon",Toast.LENGTH_SHORT).show();
}

public void OnClickDisplayToastNami(View view) {
    Toast.makeText(this,"Nami",Toast.LENGTH_SHORT).show();
}

2 个答案:

答案 0 :(得分:2)

您正在使用startActivity()导航到Fragment。这行不通。您只能在Activity中指定Intent类。

此外,请确保您在AndroidManifext.xml文件中注册每个活动,如下所示:

<application>
...
    <activity android:name="com.example.SecondActivity">
</application>

查看这篇文章,看看如何在一个活动中的多个片段之间导航:How to start Fragment from an Activity

答案 1 :(得分:1)

您无法通过startActivity函数启动片段,因此您需要这样做:

private void loadFragment(final Fragment fragment) {
    // load fragment
    try {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_container, fragment);
        transaction.commit();
        currentFragment = fragment;

    } catch (Exception e) {
        Log.d("mal", e.toString());
    }
}