Can not resolve method 'findViewById(int)'

前端 未结 9 816
孤城傲影
孤城傲影 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.

    0 讨论(0)
  • 2021-02-05 03:43

    I meet the same question in Android studio learning,just because I create the project by Fragment. Choose Blank Activity with no Fragment would solve it.

    0 讨论(0)
  • 2021-02-05 03:49

    I found solution by changing targetSdkVersion from 23 to 21

    0 讨论(0)
提交回复
热议问题