Can not resolve method 'findViewById(int)'

前端 未结 9 814
孤城傲影
孤城傲影 2021-02-05 03:08

I\'m having a trouble with findViewByid but I can\'t find where the problem is.

Here\'s my FirstFragment class code:

import and         


        
9条回答
  •  隐瞒了意图╮
    2021-02-05 03:36

    getActivity().findViewById() works. However, this isn't a good practice because the fragment may be reused in another activity.

    The recommended way for this is to define an interface.

    • The interface should contain methods by which the fragment needs to communicate with its parent activity.

      public interface MyInterfcae {
          void showTextView();
      }
      
    • Then your activity implements that Interface.

      public class MyActivity extends Activity implements MyInterfcae {
          @Override
          public void showTextView(){
              findViewById(R.id.textview).setVisibility(View.VISIBLE);
          }
      }
      
    • In that fragment grab a reference to the interface.

      MyInterface mif = (MyInterface) getActivity();
      
    • Call a method.

      mif.showTextView();
      

    This way, the fragment and the activity are fully decoupled and every activity which implements that fragment, is able to attach that fragment to itself.

提交回复
热议问题