类型参数 t 具有不兼容的上限:视图和片段

Mar*_* D. 2 java android fragment android-fragments

我想获取我的活动片段,但我收到错误:

类型参数 t 具有不兼容的上限:视图和片段

findViewById(R.id.f_instruction)我的 MainActivity 中。我希望你可以帮助我。

我的活动:

public class MainActivity extends AppCompatActivity {
Fragment f_instruction;
public static void closeFragment() {
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    f_instruction = findViewById(R.id.f_instruction);
}
Run Code Online (Sandbox Code Playgroud)

}

活动 XML:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <fragment
        android:id="@+id/f_instruction"
        android:name="e.marco.gymdiary.first_fragment"
        android:layout_width="410dp"
        android:layout_height="732dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

Sal*_*our 5

您无法通过 getViewById() 方法获取片段。这样做的正确方法是:

如果您正在活动:

Fragment fragment=getSupportFragmentManager().findFragmentById(R.id.your_fragment_id);
Run Code Online (Sandbox Code Playgroud)

如果你在片段中:

Fragment fragment=getChildFragmentManager().findFragmentById(R.id.your_fragment_id);
Run Code Online (Sandbox Code Playgroud)

这也是如何使用上下文获取片段管理器(例如,如果您在适配器中,则很有用)

((AppCompatActivity)context).getSupportFragmentManager();
Run Code Online (Sandbox Code Playgroud)