Ошибка: несовместимые типы: android.support.v4.app.Fragment не может быть преобразован в android.app.Fragment - PullRequest
0 голосов
/ 01 октября 2018

Прежде чем задать этот вопрос, я попробовал все доступные варианты и решения, представленные здесь, но безрезультатно.Учимся создавать фрагменты по этой ссылке https://abhiandroid.com/ui/fragment. В дополнение к MainActivity есть два класса фрагментов.Два класса фрагментов не выдают ошибок, но MainActivity в этой строке выполняет

fragmentTransaction.replace(R.id.frameLayout, fragment); 

в соответствии с этим методом.Аргумент «фрагмент» подчеркнут красным

private void loadFragment(Fragment fragment) {
// create a FragmentManager
    FragmentManager fm = getFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the 
//Fragment
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
    fragmentTransaction.replace(R.id.frameLayout, fragment);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit(); // save the changes
}

В сообщении об ошибке указано неверный тип аргумента 2-й.Обнаружен android.support.v4.app.Fragment требуется android.app.Fragment

, когда я наведите курсор мыши и, если перестроить, у меня будет

Ошибка: (51, 55) ошибка:несовместимые типы: android.support.v4.app.Fragment не может быть преобразован в android.app.Fragment

Для ясности я добавляю коды

MainActivity XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
    <!-- display two Button's and a FrameLayout to replace the Fragment's  -->
    <Button
        android:id="@+id/firstFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/button_background_color"
        android:text="First Fragment"
        android:textColor="@color/white"
        android:textSize="20sp" />

    <Button
        android:id="@+id/secondFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="@color/button_background_color"
        android:text="Second Fragment"
        android:textColor="@color/white"
        android:textSize="20sp" />

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="10dp" />
</LinearLayout>

MainActivity

пакет com.example.android.fragmentexample;

import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button firstFragment, secondFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Fragment fragment = new Fragment();

// get the reference of Button's
        firstFragment = (Button) findViewById(R.id.firstFragment);
        secondFragment = (Button) findViewById(R.id.secondFragment);

// perform setOnClickListener event on First Button
        firstFragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
// load First Fragment
                loadFragment(new FirstFragment());
            }
        });
// perform setOnClickListener event on Second Button
        secondFragment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
// load Second Fragment
                loadFragment(new SecondFragment());
            }
        });

    }

    private void loadFragment(Fragment fragment) {
// create a FragmentManager
        FragmentManager fm = getFragmentManager();
// create a FragmentTransaction to begin the transaction and replace the 
 //Fragment
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
// replace the FrameLayout with new Fragment
        fragmentTransaction.replace(R.id.frameLayout, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit(); // save the changes
    }
}

 FirstFragment xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.android.fragmentexample.FirstFragment">

    <!-- TODO: Update blank fragment layout -->
   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">
       <!--TextView and Button displayed in First Fragment -->
       <TextView
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_centerHorizontal="true"
           android:layout_marginTop="100dp"
           android:text="This is First Fragment"
           android:textColor="@color/black"
           android:textSize="25sp" />

       <Button
           android:id="@+id/firstButton"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:layout_centerInParent="true"
           android:layout_marginLeft="20dp"
           android:layout_marginRight="20dp"
           android:background="@color/green"
           android:text="First Fragment"
           android:textColor="@color/white"
           android:textSize="20sp"
           android:textStyle="bold" />

   </RelativeLayout>

</FrameLayout>

FirstFragment.java

package com.example.android.fragmentexample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
/**
 * A simple {@link Fragment} subclass.
 */
public class FirstFragment extends Fragment {

    View view; Button firstButton;

//    public FirstFragment() {
//        // Required empty public constructor
//    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_first, container, false);
        //get the reference of the FirstButton
        firstButton = view.findViewById(R.id.firstButton);
        //perform setOnClickListener on the firstButton
        firstButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) { 
                  //display a message by using a toast
                Toast.makeText(getActivity(), "First Fragment", 
                Toast.LENGTH_SHORT).show();


            }
        });

        return view;
    }

}

Класс secondFragment и xml-файлы аналогичны классу FirstFragment, а xml-файлы изменяют только имена, если это необходимо, для различенияот другого

Ответы [ 3 ]

0 голосов
/ 01 октября 2018

В loadFragment () вашей MainActivity используйте это

FragmentManager fm = getSupportFragmentManager();

вместо

FragmentManager fm = getFragmentManager();
0 голосов
/ 01 октября 2018

В вашей MainActivity,

просто измените эти два импорта

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

на

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

Теперь все будет работать нормально !!

0 голосов
/ 01 октября 2018

Использовать менеджер фрагментов поддержки

getSupportFragmentManager()

https://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#getSupportFragmentManager()

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...