从“活动”的“片段”视图中调用按钮

时间:2019-09-11 11:22:40

标签: java android android-studio android-activity fragment

我想在Activity方法中到达片段项,但出现空指针错误。

片段类

 Button button;

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

      final View view = inflater.inflate(R.layout.fragment, container, false);
      button= view.findViewById(R.id.button);

    return view;
    }

    public Button getButton(){
            return button;
    }

MainActivity

FragmentManager fm = getSupportFragmentManager();
Fragment fragment = (Fragment)fm.findFragmentById(R.id.Framelayout);

fragment.getButton().setText("Test");

LOGCAT

 java.lang.NullPointerException: Attempt to invoke virtual method 
 'android.widget.Button com.example.android.fragment.Fragment.getButton()' 
 on a null object reference
        at 
 com.example.android.MainActivity$1$1.onDataChange(MainActivity.java:141)

3 个答案:

答案 0 :(得分:0)

用于添加片段

<div id="dashboard-content">
<div id="sidebar">
    <div class="sidenav">
        <a class="selected">ITEM 1</a>
        <a>ITEM 2</a>
        <a>ITEM 3</a>
        <button class="dropdown-btn">ITEM4</button>
        <div class="dropdown-container">
            <a class="menu-item">SUB-ITEM 1</a>
            <a class="menu-item">SUB-ITEM 2</a>
            <a class="menu-item">SUB-ITEM 3</a>
        </div>
        <a href="giftcard.html">ITEM 4</a>
        <button class="dropdown-btn">ITEM5</button>
        <div class="dropdown-container">
            <a class="menu-item">SUB-ITEM 1</a>
            <a class="menu-item">SUB-ITEM 2</a>
            <a class="menu-item">SUB-ITEM 3</a>
        </div>
    </div>
    <div class="content visible">
        Content 1
    </div>
    <div class="content">
        Content 2
    </div>
</div>    

获取片段

private void addFragment(FragmentManager manager)
{
    YOURFRAGMENT fragment= new YOURFRAGMENT();
    FragmentTransaction transaction=manager.beginTransaction();
    transaction.add(CONTAINER-ID,fragment,YOURFRAGMENT.class.getSimpleName()).commitNow();
}

得到你的

 private void getFragment(FragmentManager manager,String TAG){
          YOURFRAGMENT fragment= (YOURFRAGMENT) manager.findFragmentByTag(TAG);
       if(fragment!=null){
       //access button here
       }
}

答案 1 :(得分:0)

使用Fragment添加TAG

String TAG="YourTAG";
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
        .replace(R.id.fragment_container, mFragment, TAG)
        .commit();

您可以像这样从您的活动中调用方法

Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG);
if (fragment instanceof YourFragmentClass ) {
    fragment.getButton().setText("Test");
}

希望它对您有帮助。

答案 2 :(得分:-2)

尝试使用getFragmentManager()而不是getSupportFragmentManager()