【问题标题】:Replace a fragment with other fragment is giving error用其他片段替换片段会出错
【发布时间】:2017-04-18 01:31:21
【问题描述】:

以下是我的代码,它在替换片段部分给出错误它说找到的参数是 android.support.v4.app.fragment 其中需要 android.app.fragment 告诉我我的代码中有什么错误我是新手,所以无法解决问题

package com.example.xainshah.fragmentexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.view.View;
import layout.Fragment1;
import layout.Fragment2;

public class MainActivity extends AppCompatActivity {

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

        Fragment fragment;
        if (view == findViewById(R.id.button)){
            fragment= new Fragment1();
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.fragment_place,fragment); \\ Error is here 2nd argument is not compatible that's what the error says 
        }

        if (view == findViewById(R.id.button)){
        fragment= new Fragment2();
            FragmentManager fm=getFragmentManager();
            FragmentTransaction ft=fm.beginTransaction();
            ft.replace(R.id.fragment_place,fragment); \\ Error is here 2nd argument is not compatible that's what the error says 
        }
        }
    }

【问题讨论】:

    标签: java android android-fragments android-fragmentactivity


    【解决方案1】:

    你必须使用支持片段管理器

    FragmentManager fm=getSupportFragmentManager();
    

    而不是

    FragmentManager fm=getFragmentManager();
    

    同时删除支持片段管理器的片段管理器的导入语句。

    【讨论】:

      【解决方案2】:

      除了使用@passiondroid 所述的“getSupportManager”之外,您正在使用

      import android.app.FragmentManager;
      import android.app.FragmentTransaction;
      

      你应该在哪里使用支持库:

      import android.support.v4.app.FragmentManager;
      android.support.v4.app.FragmentTransaction;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-04-09
        • 1970-01-01
        • 1970-01-01
        • 2012-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多