【问题标题】:TextView in Fragment Returning Null in Android Studio片段中的TextView在Android Studio中返回Null
【发布时间】:2021-11-25 17:57:09
【问题描述】:

我是 Android Studio 的新手。我在片段内的 TextView 上遇到空指针异常错误,请帮助。这是我的代码。这不过是两个片段之间的简单接口。当我单击 ListView 片段中的一个项目时,我收到空指针异常错误。确定 DetailsFragment 中的 TextView 没有分配或指向它的来源。请帮忙解决这个问题。

   public class MainActivity extends AppCompatActivity implements list_Fragment.ItemSelected {

    ArrayList<String> Descriptions = new ArrayList<String>();;
    TextView tvDescription;

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

        Descriptions.add("Description for Item 1");
        Descriptions.add("Description for Item 2");
        Descriptions.add("Description for Item 3");
        Descriptions.add("Description for Item 4");
        tvDescription = findViewById(R.id.tvDescription);
    }

    @Override
    public void onItemSelected(int index) {
        tvDescription.setText(Descriptions.get(index));
    }}

list_fragment

public class list_Fragment extends ListFragment {

    ArrayList<String> Data = new ArrayList<String>();


    ItemSelected activity;
    public interface ItemSelected{
void onItemSelected(int index);
    }

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

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        activity=(ItemSelected) context;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        Data.add("Item 1");
        Data.add("Item 2");
        Data.add("Item 3");
        Data.add("Item 4");
        setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Data));
    }

    @Override
    public void onListItemClick(@NonNull ListView l, @NonNull View v, int position, long id) {

        activity.onItemSelected(position);
    }
}

以及我认为我得到错误的详细片段代码是

public class DetailsFragment extends Fragment {

    public DetailsFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return (LinearLayout) inflater.inflate(R.layout.fragment_details, container, false);
    }
}

主 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/ll_Horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    tools:context=".MainActivity">


    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/listfragmentView"
        android:name="com.example.fragmentcheck.list_Fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="3"
        android:background="@android:color/holo_blue_dark"
        tools:layout="@layout/fragment_list_" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/detailsfragmentView"
        android:name="com.example.fragmentcheck.DetailsFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@color/purple_200"
        tools:layout="@layout/fragment_details" />
</LinearLayout>

ListFragment XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/linearLayout2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/design_default_color_primary_variant"
    android:orientation="vertical"
    tools:context=".list_Fragment">


        <ListView
            android:id="@+id/list"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
</LinearLayout>

DetailsFragment XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/design_default_color_on_secondary"
    android:orientation="vertical"
    tools:context=".DetailsFragment">


    <TextView
        android:id="@+id/tvDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/textview"
        android:textColor="#FFFFFF"
        android:textSize="20sp" />

</LinearLayout>

错误

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.fragmentcheck, PID: 28112
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object r*emphasized text*eference
        at com.example.fragmentcheck.MainActivity.onItemSelected(MainActivity.java:34)
        at com.example.fragmentcheck.list_Fragment.onListItemClick(list_Fragment.java:54)

【问题讨论】:

  • 您在DetailsFragment xml 中有tvDescription,而您在MainAcitvity 中找到它的ID。 MainActivity 只有 FragmentContainerView ,它里面没有任何文本视图。
  • 哦,好吧,由于activity_main在其中托管了两个片段,我认为这自然会继承片段中的视图。您建议我将 TextView 分配给 detailsfragment java 类中的相应 R.id 吗?我现在就试试。
  • 不,这不是它的工作原理,您无法在活动中访问片段视图 ID,tvDescription = findViewById(R.id.tvDescription); 在您的 DetailsFragment 中使用它。同样在 Details Fragment 中,您不需要将其转换为 LinearLayout
  • 当我尝试这个时,它现在显示“无法在 'DetailsFragment' 中解析方法 'findViewById'”。

标签: java android android-studio android-layout android-fragments


【解决方案1】:

tvDescriptionDetailsFragment 布局中,您需要在该类的代码中进行任何布局配置


class DetailsFragment extends Fragment {

...

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_details, container, false)
          tvDescription = view.findViewById(R.id.tvDescription);
          tvDescription.setText("some text");
       
        return view
    }

}

【讨论】:

  • 您好,先生,感谢您的重播,
  • 当我尝试这个时,它现在显示“无法在 'DetailsFragment' 中解析方法 'findViewById'”
  • 您好,我的错误,我编辑了我的答案来修复它
  • 不,先生,这与设置文本无关。我在将 tvDescriptions TextView 传递给 MainActivity java 类时遇到问题,我想根据进入某个方法的其他参数将文本设置为 TextView。我的主类 tvDescription.setText(Descriptions.get(index));
  • @two 是的 - 如果您希望在 MainActivity 中设置 tvDescription TextView,那么您需要将其添加到 Main.xml 或者您需要将数据从 MainActivity 传递到 DetailsFragment 并将其设置在那里。数据可以通过 Intents 或 Bundle args 传递
【解决方案2】:

您在 DetailsFragment xml 中有 tvDescription,而您在 MainAcitvity 中找到它的 id。 MainActivity 只有 FragmentContainerView ,里面没有任何文本视图。

您需要扩充 Fragment 的视图并在它返回的 View 上调用 findViewById()

更新了 DetailsFragment

public class DetailsFragment extends Fragment {

    TextView tvDescription;
    public DetailsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
          View view = inflater.inflate(R.layout.fragment_details, container, false)
          tvDescription = view.findViewById(R.id.tvDescription);
          tvDescription.setText("some text");
       
        return view
    }
}

【讨论】:

  • 嗨 Nitish,我已经尝试了上面的代码,但它不起作用。我仍然遇到同样的错误,我什至尝试通过添加返回方法将 tvDescription 指针从 DetailsFragment 类传递到主类,但它仍然无法正常工作。 : (
  • 为什么要将 tvDescription 从 DetailsFragment 传递给 MainActivity?如果要在片段之间进行通信,请使用事件总线或 viewmodel 。有关更多详细信息,请参阅此答案 - communcation between fragments
猜你喜欢
  • 2021-11-23
  • 2015-05-21
  • 2012-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2022-09-23
相关资源
最近更新 更多