Fragment $ InstantiationException从android.app.Activity膨胀androidx片段

问题描述 投票:1回答:2

我收到以下异常:

android.app.Fragment$InstantiationException: Trying to instantiate a class com.example.android.btVspTest.StageCollectionFragment that is not a Fragment

[在从我的android.app.Activity.setContentView类的onCreate()扩展到VspTestActivityandroid.app.Activity的以下调用中触发异常:setContentView(R.layout.activity_vsp_test);

我的com.example.android.btVspTest.StageCollectionFragment扩展了androidx.fragment.app.Fragment。我猜想这个问题与android.app.Activityandroidx.fragment.app.Fragment之间的不兼容有关。是否有修复程序或解决方法?

应用程序级别build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29

    defaultConfig {
        minSdkVersion 26
        targetSdkVersion 29
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    /*implementation 'com.google.android.material:material:1.1.0-alpha08'*/
    implementation 'androidx.viewpager2:viewpager2:1.0.0'
}

activity_vsp_test.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/test_layout">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/margin_huge"
        android:orientation="horizontal">

        <Button
            android:id="@+id/test_connect_button"
            android:layout_width="126dp"
            android:layout_height="match_parent"
            android:text="@string/connect" />

        <Button
            android:id="@+id/test_disconnect_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:text="@string/disconnect" />

        <Button
            android:id="@+id/test_bluetooth_button"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:onClick="startBluetoothActivity"
            android:text="Bluetooth" />

    </LinearLayout>

    <TextView
        android:id="@+id/vsp_test_connection_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/disconnected" />

    <TextView
        android:id="@+id/test_result_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- 2 irrelevant linear layouts with buttons in them removed -->

    <fragment class="com.example.android.btVspTest.StageCollectionFragment"
        android:id="@+id/test_stage_collection_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>

StageCollectionFragment.java:

package com.example.android.btVspTest;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.android.bluetoothvsp.R;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.android.material.tabs.TabLayoutMediator.TabConfigurationStrategy;

public class StageCollectionFragment extends Fragment implements TabConfigurationStrategy {
    // When requested, this adapter returns a StageFragment,
    // representing an object in the collection.
    StageCollectionAdapter demoCollectionAdapter;
    ViewPager2 viewPager;

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        demoCollectionAdapter = new StageCollectionAdapter(this);
        viewPager = view.findViewById(R.id.test_stage_pager);
        viewPager.setAdapter(demoCollectionAdapter);

        TabLayout tabLayout = view.findViewById(R.id.test_stage_tab_layout);
        new TabLayoutMediator(tabLayout, viewPager, this).attach();

    }

    @Override
    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
        tab.setText("OBJECT " + (position + 1));
    }
}

VspTestActivity.java:

package com.example.android.btVspTest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android.bluetoothvsp.ActivityMessageDataKey;
import com.example.android.bluetoothvsp.BluetoothActivity;
import com.example.android.bluetoothvsp.DeviceListActivity;
import com.example.android.bluetoothvsp.R;
import com.example.android.bluetoothvsp.enums.ConnectionState;
import com.example.android.bluetoothvsp.enums.TestState;
import com.example.android.common.logger.Log;
import com.example.android.common.logger.LogWrapper;
import com.example.android.common.logger.MessageOnlyLogFilter;

public class VspTestActivity extends Activity
{
    /**
     * Debugging.
     */
    private static final String TAG = "VspTestActivity";

    /**
     * UI elements.
     */
    private TextView mConnectionTextView;
    private TextView mTestResultTextView;
    private Button mConnectButton;
    private Button mDisconnectButton;
    private Button mSynchronousTestButton;
    private Button mHostSpamButton;
    private Button mReaderSpamButton;
    private Button mBothSpamButton;

    /**
     * Objects provided by Android to facilitate Bluetooth operations.
     */
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice mDevice;

    /**
     * Manger used to start and handle the communication tests.
     */
    private BluetoothVspTestManager mVspTestManager;

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

        if (savedInstanceState != null) {
            return;
        }

    // Irrelevant code removed
    }

    // Irrelevant code removed

    @Override
    protected  void onStart() {
        super.onStart();
        // Irrelevant code removed
    }

    // Irrelevant code removed
}

一些代码是https://developer.android.com/guide/navigation/navigation-swipe-view-2处的复制->粘贴->示例编辑,带有以下映射:

  • 我的StageCollectionFragment是他们的CollectionDemoFragment
  • 我的StageFragment是他们的DemoObjectFragment

很遗憾,该developer.android.com示例尚不完整,因为缺少布局资源。我还无法在Internet上找到结合TabLayout和ViewPager2的完整示例。

我正在尝试执行类似https://imgur.com/a/k8Tr52y?的草稿屏幕的操作。我最终将拥有4到5个带有实际有意义的标签标题的标签,这些标签是动态添加的,并且每个标签中都有特定的片段。

java android android-fragments androidx
2个回答
1
投票
您的活动必须扩展androidx.fragment.app.FragmentActivity

documentation开始,

想要使用基于支持的活动的基类碎片。

也来自Fragment's documentation

  • 您的活动必须扩展FragmentActivity
  • 您必须调用FragmentActivity.getSupportFragmentManager()才能获取FragmentManager

0
投票
由于您的代码的一部分正在使用AndroidX库,因此我假设您可以全力以赴并专门使用AndroidX。你应该。现在,您正在混合新旧Android库,这不是一件好事。声明时只需执行以下操作(注意导入语句):

您的活动:

import androidx.appcompat.app.AppCompatActivity;

public class VspTestActivity extends AppCompatActivity {

和您的片段:

import androidx.fragment.app.Fragment

public class StageCollectionFragment extends Fragment ...

更容易的是让Android Studio为您完成这一切。只需选择重构>迁移到AndroidX(在Mac上)

© www.soinside.com 2019 - 2024. All rights reserved.