【问题标题】:How to access Fragment's child views inside fragment's parent Activity?如何在 Fragment 的父 Activity 中访问 Fragment 的子视图?
【发布时间】:2014-06-12 15:18:08
【问题描述】:

我有一个支持的片段活动,它将加载差异片段。该片段有一些textView 和id = "score",我想获得它的句柄,但findViewById 的分数textView 返回null。为什么会这样?


textView放在fragment中

public class MyActivity extends  extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks{

   private TextView scoreBoardTextView = null;

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_home);
     mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
     scoreBoardTextView = (TextView) findViewById(R.id.score); //this returns null
  }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
      //set fragment    
    }

}

【问题讨论】:

  • 你的textview放在哪里?它在片段布局中吗?如果是,那么您必须调用 scoreBoardTextView = (TextView) findViewById(R.id.score);在片段的 onCreateView 中。像这样的东西:stackoverflow.com/questions/24156139/…
  • 在片段中。在片段中
  • 您无法从单独的 lYout 获取视图。
  • @Rod_Algonquin 没有找到你
  • 你想从Activity更新Fragment的TextView吗?您最好在 Fragment 本身中执行此操作。

标签: android android-layout


【解决方案1】:

注意:

在fragment外部直接访问fragment的视图不是一个好主意。您应该使用片段回调接口来处理此类情况并避免错误。以下方法有效,但不推荐,因为这不是一个好习惯。


如果您想在其父级Activity 中访问Fragment 的TextView,那么您应该在您的Fragment 类中定义一个方法,如下所示:
public class MyFragment extends Fragment {

    TextView mTextView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container, false);
        mTextView = (TextView) view.findViewById(R.id.textView1);
        return view;
    }

    public void setTextViewText(String value){
        mTextView.setText(value);
    }


}

现在您可以像这样在Activity 中使用它:

myFragment.setTextViewText("foo");

这里 myFragment 的类型是 MyFragment。

如果你想访问整个TextView,那么你可以在MyFragment.java中定义这样的方法:

public TextView getTextView1(){
    return mTextView;
}

通过这个你可以访问TextView本身。

希望这会有所帮助。 :)

【讨论】:

  • 这看起来是个不错的答案,但我认为覆盖显示的方法是 onCreateView() 而不是 getView()。
  • 这是正确的做法,使用 view.findViewById()
  • 你不应该这样做......为什么Activity会直接访问Fragment的视图???为什么不直接将这些视图移动到 Activity 的布局中呢?以这种方式使用片段有什么好处?
  • @kupsef 不要问我问 OP。我只是告诉它是如何完成的。我不会直接访问视图。这就是为什么我也演示了第一种方法。
  • 您可以通过一种方式实现片段,它可以告诉您特定视图是否可见。它更干净。负责视图的fragment,Activity通过fragment提供的接口获取视图的信息。没有直接访问权限。
【解决方案2】:

可以通过以下方式:

像这样在 Fragment 中保留膨胀视图的引用:

public class MyFragment extends SherlockFragment{

MainMenuActivity activity;
public View view;
public MyFragment(){
}

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

    if ( getActivity() instanceof MainMenuActivity){
        activity = (MainMenuActivity) getActivity();
    }

    view = inflater.inflate(R.layout.aboutus, container, false);        
    return view;
}

}

在Activity中创建一个函数,像这样:

 public class MainMenuActivity extends SherlockFragmentActivity {

 SherlockFragment fragment = null;

 public void switchContent(SherlockFragment fragment) {     
    this.fragment = fragment;
    getSupportFragmentManager()
    .beginTransaction()
    .replace(R.id.mainmenu, fragment)
    .commit();

    invalidateOptionsMenu();
}

它的目的是保持对当前片段的引用。每当你想切换片段时,你调用上面的函数,像这样(来自片段):

activity.switchContent( new MyFragment_2());

现在您有了当前的片段引用。所以你可以像这样在Activity中直接访问Fragment的视图:this.fragment.view

【讨论】:

  • 不错的 hack,我会试试...!
  • 父活动不应该直接操纵片段的视图。您应该在执行修改的片段内编写一个函数。直接访问片段的视图实际上使片段无用。这样就失去了封装,您最好将这些视图添加到 Activity 的布局中。
  • @kupsef 显然我们必须通过方法来访问它们,我只是为了理解而访问这里。
【解决方案3】:

您无需参考 Fragment 视图即可在 Activity 中获取其组件。因为您可以在父 Activity 中直接访问 Fragment 的布局组件。

你可以通过这个访问任何组件

findViewById(R.id.child_of_fragment_layout);  

【讨论】:

  • 确实有一点需要注意(至少对我而言),片段视图可能还没有准备好。当我将该代码移至我的活动的onStart() 时,它起作用了
【解决方案4】:

为了访问 TextView 或 Button 或片段中的任何内容,您需要执行以下操作:

public class BlankFragment extends Fragment {
public View view;
public TextView textView;
public Button button;

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

public void changeTextOfFragment(String text){
    textView.setText(text);
    view.setBackgroundResource(R.color.colorPrimaryDark);
}

一旦在您的 MainActivity 或您想从 Fragment 访问 TextView 的任何其他地方完成,您应该确保在 OnCreate() 方法中设置 Fragment,否则它很可能会抛出 nullPointer。因此,您想要更改 TextView 的活动应该看起来像这样:

public class MainActivity extends AppCompatActivity {
private Button button1;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
BlankFragment blankFragment = new BlankFragment();

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

    fragmentManager = getFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment1,blankFragment);
    fragmentTransaction.commit();
}

private void changeFragment(){
    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            blankFragment.changeTextOfFragment("Enter here the text which you want to be displayed on your Updated Fragment");

        }
    });
}

希望这会有所帮助:)

【讨论】:

    【解决方案5】:

    您可以使用 Fragment 类的 getView 方法访问。

    例如,您的 MyFragment 中有一个 TextView,其 id 为“text_view”
    在您的 Activity 中制作您的片段:

    MyFragment myFragment = new MyFragment();
    

    当您需要一个孩子时,只需调用 getView,然后找到您的 childView。

    View view = myFragment.getView();
    if (view !=null) {
    view.findViewById(R.id.text_view).setText("Child Accessed :D");
    }
    

    注意:如果你想要片段的根视图,那么myFragment.getView(); 就足够了。

    【讨论】:

    • 你的回答有问题,如果 R.id.something 是根视图,那么 getView() 就足够了
    • @cutiko 是的,getView 方法返回片段布局的根
    【解决方案6】:

    只放入fragment而不是放入activity:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_new_work_order,
        container, false);
    
        TextView scoreBoardTextView = (TextView) rootView.findViewById(R.id.score);
    
        return rootView;
    }
    

    【讨论】:

    • 我需要加载片段的父活动中的“scoreBoardTextView”活动的句柄。我该怎么做?
    • 句柄是什么意思?您需要更改 textview(text, background...) 还是需要在活动中使用 textview 中的文本?
    • 您好像对得到答案不感兴趣?
    • @Zoran 嘿,是的,我需要能够从按钮的 onClick 片段中的文本视图中获取字符串
    【解决方案7】:

    只这样做:

    ((Your_Activity) this.getActivity()).YouyActivityElements;
    

    【讨论】:

      【解决方案8】:

      如果您的 TextView 放置在 Fragment 中,那么您无法在 Fragment Parent Activity 中访问 TextView,您可以设置 Fragment 和 Activity 之间的互通接口,并在单击 TextView 或任何其他内容时发送数据你想发生

      【讨论】:

        【解决方案9】:

        您无法访问父Activity 中的Fragment 元素,但您可以通过以下方式将值传递给您的Fragment。

        在MyActivity 的onNavigationDrawerItemSelected 方法中执行以下操作

        int myScore = 100;
        @Override
        public void onNavigationDrawerItemSelected(int position) {
            // update the main content by replacing fragments
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager
                    .beginTransaction()
                    .replace(R.id.container,
                            MyFragment.newInstance(myScore)).commit();
        }
        

        在MyFragment 类中创建一个名为newInstance 的方法,如下所示

        private static final String SCORE = "score";
        public static MyFragment newInstance(int score) {
            MyFragment fragment = new MyFragment();
            Bundle args = new Bundle();
            args.putInt(SCORE, score);
            fragment.setArguments(args);
            return fragment;
        }
        

        在MyFragment的onCreateView()方法中

        @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.score);
            textView.setText(Integer.toString(getArguments().getInt(
                    SCORE)));
            return rootView;
        }
        

        仅此而已,希望对您有所帮助。如果没有,请告诉我。

        【讨论】:

          【解决方案10】:

          分数textView在fragment的布局中,不在MyActivity的布局中,即R.layout.activity_home。因此,一旦您对相应的布局文件进行膨胀,您就可以在该片段中找到乐谱文本视图。

          【讨论】:

          • 我需要加载片段的父活动中的“scoreBoardTextView”活动的句柄。我该怎么做?
          【解决方案11】:

          它返回null,因为TextView 是Fragment 的一个元素,而不是Activity。

          请注意,使用Fragment 的想法是在Fragment 中封装一个模块,这意味着Activity 不应该直接访问它的属性。考虑将您的逻辑移动到您在Fragment 中获得TextView 引用的位置

          【讨论】:

            【解决方案12】:

            只需在fragment中将TextView声明为public,在fragment的onCreateView()中通过findViewById()初始化即可。现在通过使用您在活动中添加的片段对象,您可以访问 TextView。

            【讨论】:

              【解决方案13】:

              您需要从片段视图中调用方法 findViewById。

              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_home);
                  mNavigationDrawerFragment = (NavigationDrawerFragment)
                          getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
                  scoreBoardTextView = (TextView) mNavigationDrawerFragment.getView().findViewById(R.id.score); 
              }
              

              这种方式适合我。

              【讨论】:

                【解决方案14】:

                我建议您将 textview 作为活动布局的一部分。或者,您可以将 textview 作为单独的片段。在这里查看我的question。它与您的相似,但方向相反。这是我在项目中使用的精简版代码。解释在代码中。

                活动类

                public class MainActivity extends ActionBarActivity {
                PlaceFragment fragment;
                TextView fragmentsTextView;
                
                @Override
                protected void onCreate(Bundle savedInstanceState) {
                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_main);
                }
                
                @Override
                protected void onStart() {
                    // TODO Auto-generated method stub
                    super.onStart();
                    Bundle bundle = new Bundle();
                    bundle.putString("score", "1000");
                    fragment = PlaceFragment.newInstance(bundle);
                    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                    ft.replace(R.id.container, fragment);
                    ft.addToBackStack(null);
                    ft.commit();
                    // method 1
                    // fragment is added some ways to access views
                    // get the reference of fragment's textview
                    if (fragment.getTextView() != null) {
                        fragmentsTextView = fragment.getTextView();
                    }
                    // method 2
                    // using static method dont use in production code
                    // PlaceFragment.textViewInFragment.setText("2000");
                
                    // method 3
                    // let the fragment handle update its own text this is the recommended
                    // way wait until fragment transaction is complete before calling
                    //fragment.updateText("2000");
                
                }
                
                }
                

                片段类:

                public class PlaceFragment extends Fragment {
                public TextView textViewInFragment;// to access via object.field same to
                                                    // string.length
                
                // public static TextView textViewInFragment;//to access via
                // PlaceFragment.textView dont try this in production code
                public PlaceFragment() {
                }
                
                public static PlaceFragment newInstance(Bundle bundle) {
                    PlaceFragment fragment = new PlaceFragment();
                    fragment.setArguments(bundle);
                    return fragment;
                }
                
                @Override
                public View onCreateView(LayoutInflater inflater, ViewGroup container,
                        Bundle savedInstanceState) {
                    // TODO Auto-generated method stub
                    View view = inflater.inflate(R.layout.fragment_place, container, false);
                    textViewInFragment = (TextView) view
                            .findViewById(R.id.textViewInFragment);
                    return view;
                }
                
                @Override
                public void onStart() {
                    // TODO Auto-generated method stub
                    super.onStart();
                    if (getArguments() != null) {
                        textViewInFragment.setText(getArguments().getString("score"));
                
                    }
                }
                
                public TextView getTextView() {
                    if (textViewInFragment != null) {
                        return textViewInFragment;// returns instance of inflated textview
                    }
                    return null;// return null and check null
                }
                
                public void updateText(String text) {
                    textViewInFragment.setText(text);// this is recommended way to alter
                                                        // view property of fragment in
                                                        // activity
                }
                
                }
                

                从活动到片段的通信是直截了当的。这是因为活动包含片段。保留片段对象并通过 setter 和 getter 或其中的公共字段访问其属性。但是从片段到活动的通信需要一个接口。

                【讨论】:

                  【解决方案15】:

                  为什么不直接从 FragmentPagerAdapter 访问它,

                  SubAccountFragment subAccountFragment = (SubAccountFragment) mSectionsPagerAdapter.getItem(1);
                  subAccountFragment.requestConnectPressed(view);
                  

                  这是完整的例子:

                  import android.content.Intent;
                  import android.os.Bundle;
                  import android.support.v4.app.Fragment;
                  import android.support.v4.app.FragmentManager;
                  import android.support.v4.app.FragmentPagerAdapter;
                  import android.support.v4.app.FragmentTransaction;
                  import android.support.v4.view.ViewPager;
                  import android.support.v7.app.ActionBar;
                  import android.support.v7.app.ActionBarActivity;
                  import android.view.Menu;
                  import android.view.MenuItem;
                  import android.view.View;
                  import android.widget.ImageView;
                  import android.widget.TextView;
                  
                  import java.util.Locale;
                  
                  
                  public class TabsActivity extends ActionBarActivity implements ActionBar.TabListener {
                  
                      /**
                       * 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}.
                       */
                      SectionsPagerAdapter mSectionsPagerAdapter;
                  
                      /**
                       * The {@link ViewPager} that will host the section contents.
                       */
                      ViewPager mViewPager;
                  
                      @Override
                      protected void onCreate(Bundle savedInstanceState) {
                          super.onCreate(savedInstanceState);
                          setContentView(R.layout.activity_tabs);
                  
                          // Set up the action bar.
                          final ActionBar actionBar = getSupportActionBar();
                          actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
                  
                          // 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.pager);
                          mViewPager.setAdapter(mSectionsPagerAdapter);
                  
                          // When swiping between different sections, select the corresponding
                          // tab. We can also use ActionBar.Tab#select() to do this if we have
                          // a reference to the Tab.
                          mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                              @Override
                              public void onPageSelected(int position) {
                                  actionBar.setSelectedNavigationItem(position);
                              }
                          });
                  
                          // For each of the sections in the app, add a tab to the action bar.
                          for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
                              // Create a tab with text corresponding to the page title defined by
                              // the adapter. Also specify this Activity object, which implements
                              // the TabListener interface, as the callback (listener) for when
                              // this tab is selected.
                              ActionBar.Tab tab = actionBar.newTab();
                  
                              View tabView = this.getLayoutInflater().inflate(R.layout.activity_tab, null);
                  
                              ImageView icon = (ImageView) tabView.findViewById(R.id.tab_icon);
                              icon.setImageDrawable(getResources().getDrawable(mSectionsPagerAdapter.getPageIcon(i)));
                  
                              TextView title = (TextView) tabView.findViewById(R.id.tab_title);
                              title.setText(mSectionsPagerAdapter.getPageTitle(i));
                  
                              tab.setCustomView(tabView);
                  
                              tab.setTabListener(this);
                  
                              actionBar.addTab(tab);
                          }
                      }
                  
                  
                      @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_tabs, 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_logout) {
                              finish();
                              gotoLogin();
                              return true;
                          }
                  
                          return super.onOptionsItemSelected(item);
                      }
                  
                      @Override
                      public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
                          // When the given tab is selected, switch to the corresponding page in
                          // the ViewPager.
                          mViewPager.setCurrentItem(tab.getPosition());
                      }
                  
                      @Override
                      public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
                      }
                  
                      @Override
                      public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
                      }
                  
                      /**
                       * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
                       * one of the sections/tabs/pages.
                       */
                      public class SectionsPagerAdapter extends FragmentPagerAdapter {
                  
                          public ProfileFragment profileFragment;
                          public SubAccountFragment subAccountFragment;
                          public ChatFragment chatFragment;
                  
                          public SectionsPagerAdapter(FragmentManager fm) {
                              super(fm);
                              profileFragment = new ProfileFragment();
                              subAccountFragment = new SubAccountFragment();
                              chatFragment = new ChatFragment();
                          }
                  
                          @Override
                          public Fragment getItem(int position) {
                              switch (position) {
                                  case 0:
                                      return profileFragment;
                                  case 1:
                                      return subAccountFragment;
                                  case 2:
                                      return chatFragment;
                              }
                              return null;
                          }
                  
                          @Override
                          public int getCount() {
                              // Show 3 total pages.
                              return 3;
                          }
                  
                          @Override
                          public CharSequence getPageTitle(int position) {
                              Locale l = Locale.getDefault();
                              switch (position) {
                                  case 0:
                                      return getString(R.string.title_section1).toUpperCase(l);
                                  case 1:
                                      return getString(R.string.title_section2).toUpperCase(l);
                                  case 2:
                                      return getString(R.string.title_section3).toUpperCase(l);
                              }
                              return null;
                          }
                  
                          public int getPageIcon(int position) {
                              switch (position) {
                                  case 0:
                                      return R.drawable.tab_icon_0;
                                  case 1:
                                      return R.drawable.tab_icon_1;
                                  case 2:
                                      return R.drawable.tab_icon_2;
                              }
                              return 0;
                          }
                      }
                  
                  
                      public void gotoLogin() {
                          Intent intent = new Intent(this, LoginActivity.class);
                          this.startActivity(intent);
                      }
                  
                      public void requestConnectPressed(View view){
                          SubAccountFragment subAccountFragment = (SubAccountFragment) mSectionsPagerAdapter.getItem(1);
                          subAccountFragment.requestConnectPressed(view);
                      }
                  }
                  

                  【讨论】:

                    【解决方案16】:

                    如果视图已经在屏幕上膨胀(例如可见),那么您可以像往常一样在活动中使用 findViewById(R.id.yourTextView) ,它将返回文本视图的句柄,或者如果视图是 null没找到。

                    【讨论】:

                      【解决方案17】:

                      我只是使用方法从父活动中访问片段视图,因为我们创建了一个新的片段类对象来插入片段。所以我很喜欢这个。

                      class BrowserFragment : Fragment(), Serializable {
                          private lateinit var webView: NestedScrollWebView
                          override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
                              webView = view.findViewById(R.id.web_view)
                          }
                          fun getWebView(): WebView {
                              return webView
                          }
                      }
                      

                      在MainActivity

                      val browserFragment = BrowserFragment()
                      val fragmentTransaction = supportFragmentManager.beginTransaction()
                      fragmentTransaction.add(R.id.browser_fragment_placeholder, browserFragment)
                      fragmentTransaction.commit()
                      
                      val webView = browserFragment.getWebView()
                      

                      【讨论】:

                        猜你喜欢
                        • 2014-05-17
                        • 1970-01-01
                        • 2014-12-23
                        • 2021-03-16
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多