片段通信问题(尝试调用虚方法)

Posted

技术标签:

【中文标题】片段通信问题(尝试调用虚方法)【英文标题】:Problem with fragment communication(Attempt to invoke virtual method) 【发布时间】:2020-04-12 12:21:01 【问题描述】:

我有一个带有 2 个片段的选项卡式活动。我正在尝试将字符串从第一个片段传输到第二个片段,但我得到了 NULL POINTER EXCEPTION。 这是 MainActivity.java:

package com.example.myapplication;

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

import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.ui.main.SectionsPagerAdapter;

public class MainActivity extends AppCompatActivity implements Frag1.Exchange 

    private static final String TAG = "MainActivity";

    private SectionsPagerAdapter sectionsPagerAdapter;

    private ViewPager viewPager;

    private TabLayout tabLayout;

    private void setupViewPager(ViewPager viewPager)
        SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        sectionsPagerAdapter.addFragment(new Frag1(), "FirstTab");
        sectionsPagerAdapter.addFragment(new Frag2(), "SecondTab");
        viewPager.setAdapter(sectionsPagerAdapter);
    

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

        sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        viewPager = (ViewPager) findViewById(R.id.view_pager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

    

    @Override
    public void stringExchange(String s) 
        Frag2 frag2 = (Frag2) getSupportFragmentManager().findFragmentByTag("SecondTab");
        frag2.displayExchange(s);
    

这里是 SectionsPagerAdapter.java

package com.example.myapplication.ui.main;

import android.content.Context;

import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;

import com.example.myapplication.R;

import java.util.ArrayList;
import java.util.List;

/**
 * A [FragmentPagerAdapter] that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentPagerAdapter 

    private final List<Fragment> fragmentList = new ArrayList<>();
    private final List<String> stringList = new ArrayList<>();

    public void addFragment(Fragment fragment, String title)
        fragmentList.add(fragment);
        stringList.add(title);
    

    public SectionsPagerAdapter(FragmentManager fm) 
        super(fm);
    

    @Override
    public Fragment getItem(int position) 
        // getItem is called to instantiate the fragment for the given page.
        // Return a  (defined as a static inner class below).
        return fragmentList.get(position);
    

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) 
        return stringList.get(position);
    

    @Override
    public int getCount() 
        // Show 2 total pages.
        return fragmentList.size();
    

这里是 Frag1.java:

package com.example.myapplication;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;


public class Frag1 extends Fragment
    private static final String TAG = "FirstTab";
    private Button transfer;
    private Exchange ex;

    public interface Exchange
        public void stringExchange(String s);
    

    @Nullable
    @Override
    public View onCreateView(@NonNull final LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) 
        final View view = inflater.inflate(R.layout.tab1_fragment, container, false);
        transfer = (Button) view.findViewById(R.id.button2);
        ex = (Exchange) getActivity();

        transfer.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                String s = "Test";
                ex.stringExchange(s);
            
        );
        return view;
    



使用它的 xlm tab1_fragment.xlm:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_
    android:layout_
    android:padding="16dp"
    android:id="@+id/tab1"
    >
    <Button
        android:id="@+id/button2"
        android:layout_
        android:layout_
        android:text="@string/transfer"
        android:layout_centerInParent="true"/>

</RelativeLayout>

最后是Frag2.java:


package com.example.myapplication;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;

public class Frag2 extends Fragment 
    private static final String TAG = "SecondTab";
    private ListView listView;
    private ArrayList<String> arrayList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
        View view = inflater.inflate(R.layout.tab2_fragment, container, false);
        listView = (ListView) view.findViewById(R.id.list_view);
        ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,arrayList);

        listView.setAdapter(arrayAdapter);

        return view;
    

    public void displayExchange(String s)
        arrayList.add(s);
    



当我调用 findFragmentByTag("SecondTab") 时,我认为问题出在 MainActivity 中,因为它的标签未设置为 SecondTab,但我不知道如何设置它。 任何帮助将不胜感激!

【问题讨论】:

【参考方案1】:

使用 ViewModel 在 Fragment 之间共享数据。参考:https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing

【讨论】:

以上是关于片段通信问题(尝试调用虚方法)的主要内容,如果未能解决你的问题,请参考以下文章

如何使用接口在片段和活动之间进行通信?

Android 调用组件 w/listener 或让 viewmodel 调用组件与片段通信

在tablayout片段之间进行通信[重复]

尝试调用虚方法'void android.view.View.setOnClickListener [duplicate]

SearchView 尝试在空引用上调用虚方法

无法通过接口获取与片段通信的活动