title: Fragment vs. Custom View in Android
body: <p>The Fragment and Custom View can achieve the similar function, I know that fragment is more re-usable comparing with custom view, any other benefits/enhancements for using Fragment? Is fragment supposed to replace Custom View, or just a enhancement for some specific purpose? </p>
  
  <p>For instance, the code below is <strong>fragment</strong>: </p>
  
  <pre><code>public class TestFragment extends Fragment {
  
      private TextView tv_name;
      private Button btn_play;
      private Button btn_delete;
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          return inflater.inflate(R.layout.testfragment, container, false);
      }
  
      @Override
      public void onStart() {
          super.onStart();
  
          tv_name = (TextView)getView().findViewById(R.id.tv_name);
          btn_play = (Button)getView().findViewById(R.id.btn_play);
          btn_delete = (Button)getView().findViewById(R.id.btn_delete);
  
      }
  }
  </code></pre>
  
  <p>The code for <strong>custom view</strong>: </p>
  
  <pre><code>public class TestCustomView extends LinearLayout {
  
      private TextView tv_name;
      private Button btn_play;
      private Button btn_delete;
  
      public TestCustomView(Context context, AttributeSet attrs){
          super(context, attrs);
  
          setOrientation(LinearLayout.HORIZONTAL);
          setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
  
          tv_name = new TextView(context);
          addView(tv_name);
  
          btn_play = new Button(context);
          addView(btn_play);
  
          btn_delete = new Button(context);
          addView(btn_delete);
      }
  
      public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          return inflater.inflate(R.layout.testfragment, container, false);
      }
  }
  </code></pre>
  
  <p>Both <code>TestFragment</code> and <code>TestCustomView</code> can create a view consisting of <code>TextView</code> and <code>Buttons</code>, and use tags of <code>Framelayout/fragment</code> and <code>com.packagename.TestCustomView</code> to declare in the activity's xml layout file, but what's the advantages to use Fragment?</p>