如何从父活动的片段访问视图?

时间:2019-01-06 07:49:21

标签: android android-fragments

嗨,我想通过单击片段中的按钮来查找如何替换片段。

我尝试研究了此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()'   在空对象引用上

1 个答案:

答案 0 :(得分:2)

您可以这样做:

接口:

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 

        }



}