java - 类型参数 t 具有不兼容的上限 : view and fragment

标签 java android android-fragments fragment

我想获取我的 Activity fragment ,但我收到错误:

type parameter t has incompatible upper bounds: view and fragment

通过我的 MainActivity 中的 findViewById(R.id.f_instruction) 。 我希望你能帮助我。

我的 Activity :

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);
}

}

Activity 的 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>

最佳答案

您无法通过 getViewById() 方法获取 fragment 。正确的方法是:

如果您正在 Activity :

Fragment fragment=getSupportFragmentManager().findFragmentById(R.id.your_fragment_id);

如果你在 fragment 中:

Fragment fragment=getChildFragmentManager().findFragmentById(R.id.your_fragment_id);

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

((AppCompatActivity)context).getSupportFragmentManager();

关于java - 类型参数 t 具有不兼容的上限 : view and fragment,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60237650/

相关文章:

没有 TLS 的 Android P : network-security-config: cleartextTrafficPermitted not possible for IP (only domain)

java - 如何在 java/android 中漂亮地格式化 GPS 数据?

android - 图像查看器 fragment (Android)

java - 用于从链接列表轮询消息的基于事件的模型

android - 如何在 Android(模拟器)中查找和清除 SQLite 数据库文件

java - 在知道@NonNull 注释的Eclipse 中自动生成equals 和hashCode

android - fragment 相互重叠显示

android - 在 Activity 之间保留 fragment 状态

java - 在 Kotlin 中将函数调用分配给变量

c# - WPF 中的 SwingUtilities.invokeLater 等价物