Android - Fragment

摘要:Android - Fragment

如果我有常使用的元件,而且是一堆view的組合,

我們可以將他包成Fragment來處理(如同ASP.NET的User Control)

Control製作,分,Class與xml layout  ,再來如何使用

xml layout 

fragment_custom_button.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_wrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="horizontal"
    android:padding="8dp" >

    <TextView
        android:id="@+id/custom_btn"
        android:layout_width="362dp"
        android:layout_height="67dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:clickable="true"
        android:focusable="true"
        android:gravity="center"
        android:padding="16dp" />
</LinearLayout>

Class則如下

public class CustomButtonFragment extends Fragment implements OnClickListener{
    
    private View mCustomBtnContainer;
    private TextView mCustomBtn;
     
    public static CustomButtonFragment newInstance() {
        CustomButtonFragment frag = new CustomButtonFragment();
        return frag;
    }
    
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_custom_button, null, false);
    }
    
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }
    
    @Override
    public void onDetach() {
        super.onDetach();
        mCustomBtnContainer = null;
        mCustomBtn = null;
    }
    

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        AQuery aq = new AQuery(getView());
        mCustomBtnContainer = aq.id(R.id.custom_wrapper).getView();
        mCustomBtnContainer.setVisibility(View.GONE);
        mCustomBtn = (TextView) aq.id(R.id.push_custom_btn).clicked(this).getView();
    }
    
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.custom_btn) {
            //do something
        }
    }

}

 

使用時,也分layout與xml

layout 插入如下

    <FrameLayout
        android:id="@+id/frag_custome_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Class使用如下

    protected void replaceFragment() {
        Fragment frag = CustomButtonFragment.newInstance();

        if (frag != null) {
            getFragmentManager().beginTransaction()
                    .replace(R.id.frag_custome_button, frag)
                    .commit();
        }
    }