android - 使用 Fragment 内的方法更改 TextView 值 (NullPointerException)

标签 android android-layout android-fragments nullpointerexception findviewbyid

我正在尝试制作一个应用程序(用于学习目的),其中有一些带有可滚动内容的选项卡。 我有一个折叠的应用程序栏,其中一个 ViewPager 作为主布局,以及三个相同的布局,其中一个 NestedScrollView 内有一个 TextView,其中唯一的区别是文本顶部的图像。我还有三个 fragment 类,里面有相同的代码。一切正常。

但是由于我在每个选项卡中使用相同的布局,我认为我可以只拥有每个选项卡中的一个,而不是每个选项卡的 xml 文件和 java 类,然后以某种方式更改我的内部每个选项卡的内容适配器。

所以我尝试在我的 tabFragment 类中创建一个方法来执行此操作。但我似乎找不到修改 TextView 的方法。我每次都会收到 NullPointerException。

我错过了什么? 我的做法有错吗?如果是的话,什么是更好的呢?我该如何解决这个问题?

提前谢谢你:)

<小时/>

这是我现在的 fragment 类(仅剩下一个):

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import com.example.tablayoutwithscrollview.R;

public class TabFragment extends Fragment {

    private TextView textView;
    private int text, image;

    public TabFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.tab1, container, false);
        //textView = view.findViewById(R.id.textView);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);
        textView = getView().findViewById(R.id.textView);
    }

    public void setTabContent(int text, int image)
    {
        textView.setText(text);
        textView.setCompoundDrawablesWithIntrinsicBounds(0,image,0,0);
    }
}

我的适配器类:

import android.content.Context;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.example.tablayoutwithscrollview.Tabs.TabFragment;

public class MyAdapter extends FragmentPagerAdapter {

    private static int tabCount;
    Context context;

    public MyAdapter(FragmentManager fm, int tabCount, Context context){
        super(fm);
        this.tabCount = tabCount;
        this.context = context;
    }

    @Override
    public Fragment getItem(int position) {

        TabFragment fragment;
        switch (position)
        {
            case 0:
                fragment = new TabFragment();
                fragment.setTabContent(R.string.lorem_ipsum, R.drawable.jackfruit);
                return fragment;
            case 1:
                fragment = new TabFragment();
                fragment.setTabContent(R.string.lorem_ipsum, R.drawable.guava);
                return fragment;
            case 2:
                fragment = new TabFragment();
                fragment.setTabContent(R.string.lorem_ipsum, R.drawable.pomegranate);
                return fragment;
            default:
                return null;
        }
    }

    @Override
    public CharSequence getPageTitle(int position)
    {
        switch (position)
        {
            case 0:
                return context.getString(R.string.tab1_title);
            case 1:
                return context.getString(R.string.tab2_title);
            case 2:
                return context.getString(R.string.tab3_title);
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return tabCount;
    }
}

主要 Activity :

package com.example.tablayoutwithscrollview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.widget.NestedScrollView;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;

import com.google.android.material.tabs.TabLayout;

public class MainActivity extends AppCompatActivity {

    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager = findViewById(R.id.viewPager);
        populatesTabLayout(tabLayout);
        MyAdapter myAdapter = new MyAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), this);
        viewPager.setAdapter(myAdapter);

        tabLayout.setupWithViewPager(viewPager);
    }

    private void populatesTabLayout(TabLayout tabLayout)
    {
        for (int i = 0; i<3; i++)
        {
            tabLayout.addTab(tabLayout.newTab());
        }
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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/coordLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBarLayout"

        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapseToolBar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"

            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|exitUntilCollapsed"
            app:toolbarId="@+id/toolbar">


            <ImageView
                android:id="@+id/imageView7"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:srcCompat="@drawable/strawberry" />

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"></androidx.appcompat.widget.Toolbar>

        </com.google.android.material.appbar.CollapsingToolbarLayout>

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:visibility="visible" />

    </com.google.android.material.appbar.AppBarLayout>


    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


</androidx.coordinatorlayout.widget.CoordinatorLayout>

我的标签布局:

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/tabNestedScrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:drawableTop="@drawable/jackfruit"
        android:text="@string/lorem_ipsum" />
</androidx.core.widget.NestedScrollView>

这是它应该如何工作的(从以前开始,每个选项卡都有一个 fragment 类和一个布局文件): enter image description here enter image description here enter image description here

最佳答案

问题是创建的 TabFragment 实例尚未附加到 Activity,因此此时 textView 并未膨胀。

您应该将文本作为 MyAdapter#getItem(..) 方法中的参数传递给 TabFragment 实例。

...    
case 0:
   fragment = new TabFragment();

   Bundle args = new Bundle();
   args.putString("key", textString);
   fragment.setArguments(args);
   return fragment
...

之后在 onViewCreated(...) 方法中设置 TextView 实例的文本:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    textView = getView().findViewById(R.id.textView);
    textView.setText(getArguments().getString("key"));
}

或者你可以在 Android Reference 看到一个很好的例子。 .

关于android - 使用 Fragment 内的方法更改 TextView 值 (NullPointerException),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58826612/

相关文章:

android - 在没有 LifecycleObserver 的情况下使用 LiveData

android - 为什么我在自定义 RecyclerView 中的项目图像在滚动时会发生变化?

android - GetTY allState 始终返回空闲状态

android - 在 Android 应用程序中生成条形码图像

android - 如何修复在 Nexus 设备中出现移动的导航栏?

java - 如何使用 androidx 从另一个 fragment 调用 fragment 方法

Android 复杂表格布局

android - 如何将图像移动到 x、y 坐标与当前比例和填充的位置

android - 如何在 fragment 中使用 ViewPager

android - DialogFragment 和后退按钮