【问题标题】:type parameter t has incompatible upper bounds: view and fragment类型参数 t 具有不兼容的上限:视图和片段
【发布时间】:2020-02-15 09:57:45
【问题描述】:

我想获取我的 Activity 片段,但出现错误:

类型参数 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);
}

}

活动的 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>

【问题讨论】:

    标签: java android android-fragments fragment


    【解决方案1】:

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

    如果你在活动:

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

    如果你在片段中:

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

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

    ((AppCompatActivity)context).getSupportFragmentManager();
    

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题。这帮助我解决了问题:

      1. 转到您的“activity_main.xml”
      2. 右键 -> 重构 -> 重命名(或使用 SHIFT + F6)
      3. 例如将布局重命名为“activity_main2.xml”
      4. 将此文件重命名回原来的“activity_main.xml”

      【讨论】:

        猜你喜欢
        • 2020-02-16
        • 2015-11-17
        • 2018-05-05
        • 2016-03-25
        • 2014-02-23
        • 1970-01-01
        • 2013-08-15
        • 1970-01-01
        相关资源
        最近更新 更多