当前位置: 首页 > 知识库问答 >
问题:

对片段调用getView将返回null

华建同
2023-03-14

正如您在onCreate方法中看到的,我在“片段”列表的第0个片段上调用了getView。它返回null。我试着在代码中加入一个计时器,让它每秒运行一次,并检查视图是否为空。在计时器的第二个滴答声中,视图不为空。大体上

主要活动。JAVA

package com.axinite.standapp;

import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.view.ViewParent;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

public class MainActivity extends AppCompatActivity {

    int i = 0;

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    int standUpSeconds = 4000;

    List<android.support.v4.app.Fragment> fragments = new Vector<android.support.v4.app.Fragment>();

    NumberPicker SUPickerH;
    NumberPicker SUPickerM;
    NumberPicker SUPickerS;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        fragments.add(Fragment.instantiate(this, BlankFragment.class.getName()));

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), fragments);
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);
        tabLayout.setSelectedTabIndicatorColor(Color.WHITE);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        final int[] ICONS = new int[] {
                R.drawable.walking,
                R.drawable.iris
        };
        for (int i=0; i < tabLayout.getTabCount(); i++)
        {
            tabLayout.getTabAt(i).setIcon(getDrawable(ICONS[i]));
        }//endfor)
        View view = ((BlankFragment) fragments.get(0)).getView();
        if(view != null) {
            TextView tv = (TextView) view.findViewById(R.id.glupost);
            tv.setText("dasdas");
            //Toast.makeText(getApplicationContext(), ((Fragment) fragments.get(0)).toString(), Toast.LENGTH_SHORT).show();
        }
    }

    void Setup() {



    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        List<Fragment> fragments;
        public SectionsPagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {

            return "";
        }
    }
}

空白碎片。JAVA

    package com.axinite.standapp;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link BlankFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link BlankFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BlankFragment extends Fragment {

    protected View mView;
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BlankFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BlankFragment newInstance(String param1, String param2) {
        BlankFragment fragment = new BlankFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

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

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {

        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

}

共有1个答案

陈飞
2023-03-14

活动与其片段通信的典型方法如下:

MyFragment frag = (MyFragment) getFragmentManager().findFragmentById(R.id.container_of_fragment);
frag.getMyTextView().setText("New text");

或(通常首选IMO)

MyFragment frag = (MyFragment) getFragmentManager().findFragmentByTag("fragment_tag_string_value");
frag.getMyTextView().setText("New text");

然而,如果使用ViewPager,这会变得更加困难,因为容器的“id”就是ViewPager本身,它包含多个片段。此外,没有一个内置的适配器机制(我知道)来为片段设置标记。

我可以想出两种方法来避免这种情况。首先,您可以使用EventBus,比如GreenRobot的EventBus,或者AndroidAPI中的LocalBroadcastManager。GreenRobot的EventBus也是回答类似问题的推荐技术。

另一种选择是利用这样一个事实,即一个片段总是有一个对其宿主活动的引用,这意味着片段可以通过一个接口从活动请求文本,该接口将文本返回给片段

public class MainActivity implements FragmentOne.Callbacks {

    //...
    @Override
    public String requestTextViewString() {
        return "Text to send to Fragment"
    }

在你假设的片段内:

public class FragmentOne extends Fragment {

    private Callbacks mCallback;
    private TextView mTextView;

    public interface Callbacks {
        String requestTextViewString();
    }

    @Override
    public void onAttach(Activity activity) {
        if (activity instanceof Callbacks) {
            mCallback = (Callbacks) activity;
        }
    }

/*
*Later in your Fragment, when you want to get text from your MainActivity
* i.e. in onCreateView()
*/
    mTextView.setText(mCallback.requestTextViewString());

编辑:还要记住,试图从活动中的onCreate()访问片段可能会导致空点异常。这张图显示了这两个生命周期彼此并排。然而,这不应该是一个问题,因为在片段的“设置”生命周期事件期间所需的任何内容都可以作为片段的newInstance()方法中的参数传递:

public class FragmentOne extends Fragment {

    private static final String KEY = "text_for_text_view_key";

    public static FragmentOne newInstance(String textForTextView) {
        Bundle args = new Bundle();
        FragmentOne frag = new FragmentOne();
        args.putString(KEY, textForTextView);

        frag.setArguments(args);
        return frag;
    }

//And when required...
    mTextView.setText(getArguments().getString(KEY));

 类似资料:
  • 我正在尝试将Map放入一个片段中。我正在粘贴我正在使用的代码 XML 下面是我声明的片段名称 下面是我如何初始化地图 这个方法是在onCreateView上调用的 错误是 请帮助解决此问题。问题在下面部分 编辑1 将xml更改为 和 和初始化 但同样的错误是 这发生在排队的时候 为什么会发生这种情况?? 编辑2 对getmap已弃用。所以我试过了 和 以及回调。。 和setUpMap方法 错误显示

  • 这是我的代码,根据文档,它是用于: 我在这里找到了一个解决方案,但我并不真正理解它,因为它是用编写的,我也不理解。我需要帮助!! ---编辑----

  • 在我片段中,我从图库中选择了照片 在manifest.xml中 在此之前,我的应用程序显示权限对话框。我按允许 此处请求权限对话框:

  • 我正在调用tabhost片段活动中的映射片段

  • 我在使用FragmentPagerAdapter时遇到问题。我想从视图寻呼机中的片段中检索数据。当我调用getItem()方法时,它返回一个片段,但不创建片段。所有片段变量均为null。我需要做什么来实例化片段?这是我的适配器。 这是viewpager中的片段。 我不太了解ViewPager是如何工作的,但据我所知,片段在没有设置任何变量的情况下返回的原因是因为ViewPager没有附加片段。如何

  • 我在过去的两个小时里一直在试图解决这个问题。试过很多东西。 该片段似乎正在向我的适配器传递空上下文。我尝试在onCreate和onCreateView和onActivityCreated中初始化上下文变量。同样的结果。