【问题标题】:Random fragment gets updated with setText随机片段使用 setText 更新
【发布时间】:2016-03-09 18:56:24
【问题描述】:

我有一个包含一个活动和三个片段的 Android 项目。所有片段上都有相同的视图项。它基于 TabbedActivity 示例项目。这会创建同一个片段视图的多个实例。

所有的编辑框都有相同的 id: android:id="@+id/editText2"

片段上有相同的按钮和相同的编辑框,按下按钮会启动一个网络活动,尝试更新同一片段上的编辑框。

    final EditText resultBox = (EditText) findViewById(R.id.editText2);

    System.out.println("reponse: " + decodedStr);
    try 
    {
        runOnUiThread(new Runnable() 
        {
    
        @Override
        public void run() {
            resultBox.setText(decodedStr);
        }
         });
    }

但只有一个片段被更新,有时甚至不是活动片段。当我执行 findViewById(R.id.editText2);

时,这里到底发生了什么

编辑:添加了更多代码,结果 getText 函数也获取了错误的数据:

public class MainActivity extends AppCompatActivity {

    /**
     * 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;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }



    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_PAGE_TITLE = "page_title";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(String pageTitle) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putString(ARG_PAGE_TITLE, pageTitle);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getString(ARG_PAGE_TITLE)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        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 PlaceholderFragment (defined as a static inner class below).

            String pageTitle;
            switch (position)
            {
                case 0:
                    pageTitle = "1";
                    break;
                case 1:
                    pageTitle = "2";
                    break;
                case 2:
                    pageTitle = "3";
                    break;
                default:
                    pageTitle = "4";
                    break;
            }
            return PlaceholderFragment.newInstance(pageTitle);
        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
            }
            return null;
        }
    }

    /** Called when the user touches the button */
    public void randomFunc(View view) {
        try {

            // Get the current Fragment in View using the ViewPager's currentItem
            PlaceholderFragment fragment = (PlaceholderFragment) mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());
            // Get the current Fragment's View
            View fragview = fragment.getView(); // Same view that onCreateView returns
            System.out.println("fragView " + fragview); // NULL

            EditText et = (EditText) fragview.findViewById(R.id.editText); // CRASH!!

...
        }
        catch (Exception e)
        {
            System.out.println("func failed" + e.toString());
        }
    }

}

在xml中:

android:onClick="randomFunc"

【问题讨论】:

  • 最终 EditText resultBox = (EditText) findViewById(R.id.editText2);可以改成最终的EditText resultBox = (EditText) fragmentView.findViewById(R.id.editText2);
  • 为什么不创建edittext视图的类成员变量引用,然后在运行方法中使用!当您执行 findViewById 时会发生什么情况,它会从您初始化 findViewById 的视图中对您的层次结构树进行 BFS 遍历
  • 请将 Activity 和片段代码粘贴到您要更新 EditText 的位置。

标签: android android-fragments fragment


【解决方案1】:

我假设您使用 ViewPager,以便更新正确的片段:

// Get the current Fragment in View using the ViewPager's currentItem
PlaceholderFragment fragment = (PlaceholderFragment) mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());
// Get the current Fragment's View
View view = fragment.getView();
// Find the view your looking for, and update its text
final EditText resultBox = (EditText) view.findViewById(R.id.editText2);
try {
    runOnUiThread(new Runnable() {

    @Override
    public void run() {
        resultBox.setText(decodedStr);
    }
     });
}

【讨论】:

  • 感谢您的回复。是的,我确实在使用 ViewPager。我尝试了上面的示例,但由于某种原因,fragment.getView() 返回 null。什么可能导致这种情况? onCreateView 函数返回一个不为空的 rootView。
  • @ellont 您可以发布您的活动和片段代码,以及您使用的网络代码,或者创建一个要点并分享网址
  • @ellont 这个片段视图返回 null 因为你留下了样板代码,它总是在调用 getItem 时返回片段的新实例,实例化时没有关联视图,因为 onCreateView 回调不是立即被调用。您应该改为创建一个 List 并在那里跟踪 Fragment 并在给定索引处返回 Fragment 而不是依赖样板代码
  • 好的,现在知道了。但不应该是跟踪的 FragmentManager 还是碎片?
  • @ellont 片段管理器确实会跟踪片段,是的,但是由于您总是返回片段的新实例,它正在管理这些片段而不是现有片段
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多