【问题标题】:How do I access a view from a Fragment from the Parent Activity?如何从父活动的片段访问视图?
【发布时间】:2019-01-06 17:29:25
【问题描述】:

您好,我正在尝试通过单击片段中的按钮来了解如何替换片段。

我尝试查看此article,但它对我不起作用。

 View view = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getView();
    btnGoToSignUp = view.findViewById(R.id.btnGoToSignUp);

我试过了,但它出现了错误

原因:java.lang.NullPointerException:尝试调用虚拟 方法'android.view.View android.support.v4.app.Fragment.getView()' 在空对象引用上

【问题讨论】:

  • getSupportFragmentManager().findFragmentById(R.id.fragment_container)=null 这意味着您的片段甚至不存在,即当您尝试访问片段的视图时片段被破坏

标签: android android-fragments


【解决方案1】:

你可以这样做:

界面:

public interface BtnClickable {
    void myClickMethod(View v);
}

片段:

    public class SomeFragment  {
BtnClickable btnClickable;
    //...onCreateView, etc.

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_add_note, container, false);
    Button btnGoToSignUp = root.findViewById(R.id.btnGoToSignUp);

    btnGoToSignUp.setOnClickListener(new OnClickListener() {
        public void onClick(View v)
        {
    btnClickable.myClickMethod(v);
        } 
    });



    }
public static void setClickListener(BtnClickable listener){
btnClickable=listener;
}

活动:

    class MyActivity implements BtnClickable {

        //...onCreate etc instantiating your fragments
               public void onCreate(Bundle savedInstanceState)
    {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.filters); 
        SomeFragment.setClickListener(this); 

    }

        public void myClickMethod(View v) {
       // you can listen here for btn clicked 

        }



}

【讨论】:

  • 嗨,我认为你在正确的道路上,但我有这个错误 java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.android.memo.FragmentCommunicator.changeFragment(android .view.View, java.lang.String)' 在空对象引用上
猜你喜欢
  • 2014-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多