java——android studio中关于片段的困惑

8ftvxx2r  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(328)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

三年前关门了。
改进这个问题
这是我学习android工作室的第二天。我不知道这里为什么会出错。请帮帮我

//MainActivity.java
    public void ChangeFragment(View view) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment2 fragment2 = new Fragment2();
        fragmentTransaction.add(R.id.FragmentView, fragment2);   
//error is there: "Wrong 2nd argument type. Found: 'com.example.myfirstapp.Fragment2', required: 'android.app.Fragment'"

        fragmentTransaction.commit();
    }

@

//Fragment2.java
import android.support.v4.app.Fragment;
public class Fragment2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.activity_fragment2, container, false);

        Button button1 = (Button) view.findViewById(R.id.button2);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView text = (TextView) view.findViewById(R.id.textView1);
                text.setText("I am a Fragment");
            }
        });
        return view;
    }

@

//activity_fragment2.xml
    <LinearLayout
        android:id="@+id/FragmentView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:layout_editor_absoluteX="16dp"
        tools:layout_editor_absoluteY="16dp">
    </LinearLayout>

https://developer.android.com/guide/components/fragments.html#transactions

ebdffaop

ebdffaop1#

如果您正在使用 android.support.v4.app.Fragment (你应该),那么你需要使用 getSupportFragmentManager() ,不是 getFragmentManager() .

woobm2wo

woobm2wo2#

import android.app.FragmentManager;
import android.app.FragmentTransaction;
FragmentManager fragmentManager =**getFragmentManager()**;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

import android.app.Fragment;
public class Fragment2 extends Fragment {..}

@

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
FragmentManager fragmentManager =**getSupportFragmentManager()**;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

import android.support.v4.app.Fragment;
public class Fragment2 extends Fragment {..}

相关问题