[英]Starting a new Activity causes the app to restart
我創建了一個按鈕,它將打開一個新活動,但是當我啟動應用程序並單擊該按鈕時,應用程序會立即重新啟動,而不會出現任何 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);
}
}
這是一個片段類,其中第一類是 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();
}
您正在使用startActivity()
導航到Fragment
。 這不起作用。 您只能在Intent
指定Activity
類。
此外,請確保在AndroidManifext.xml
文件中注冊每個活動,如下所示:
<application>
...
<activity android:name="com.example.SecondActivity">
</application>
查看這篇文章,了解如何在一個 Activity 中的多個 Fragment 之間導航: 如何從一個 Activity 啟動 Fragment
你不能通過 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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.