Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android開發---Fragment學習總結(一)

Android開發---Fragment學習總結(一)

編輯:關於Android編程

下面正式開始Fragment使用講解:

一.准備工作
1.引入類庫(導包)
步驟:復制jar包--->project視圖下--->工程--->app--->libs粘貼--->右鍵jar包--->Add as Library--->ok
導入成功!
注意:在android.os和support.v4包裡都有Fragment類,使用的時候注意統一,要用就一直用一個,否則會引起混亂和bug.


2.v4包的意義
兼容低版本.如果不考慮兼容安卓低版本,那麼不用導入該類庫.


3.快速識別v4包和不同包的Fragment
v4包的Fragment經常會有support的字樣


二.使用方法
(在此以仿微信TAB選項卡的Fragment方式舉例說明,首頁列表顯示PackageManager類取到的手機App信息):

---------------------------------效果演示----------------------------------

\

 

---------------------------------工程結構----------------------------------

\

 

1.Fragment布局

(1)主布局

 



    
    

    
    <framelayout android:id="@+id/id_content" android:layout_height="0dp" android:layout_weight="1" android:layout_width="match_parent"></framelayout>

    
    
    

 

(2)Fragment嵌套ListView布局

 



    

 

2.Java關鍵代碼

(1)MainActivity

 

public class MainActivity extends Activity implements View.OnClickListener {

    //tab
    private LinearLayout mTabWeixin;
    private LinearLayout mTabContact;
    private LinearLayout mTabFind;
    private LinearLayout mTabUser;

    //imgb
    private ImageButton mImgbWeixin;
    private ImageButton mImgbContact;
    private ImageButton mImgbFind;
    private ImageButton mImgbUser;

    //frg
    private Fragment mFrgWeixin;
    private Fragment mFrgContact;
    private Fragment mFrgFind;
    private Fragment mFrgUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        //初始化控件
        initView();

        //初始化事件
        initEvent();

        //初始化狀態
        setSelect(0);
    }

    private void initEvent() {
        mTabWeixin.setOnClickListener(this);
        mTabContact.setOnClickListener(this);
        mTabFind.setOnClickListener(this);
        mTabUser.setOnClickListener(this);
    }

    private void resetImgb() {
        mImgbWeixin.setImageResource(R.drawable.weixinoff);
        mImgbContact.setImageResource(R.drawable.contactoff);
        mImgbFind.setImageResource(R.drawable.findoff);
        mImgbUser.setImageResource(R.drawable.useroff);
    }

    private void initView() {
        //tab
        mTabWeixin = (LinearLayout) this.findViewById(R.id.ll_tab_weixin);
        mTabContact = (LinearLayout) this.findViewById(R.id.ll_tab_contact);
        mTabFind = (LinearLayout) this.findViewById(R.id.ll_tab_find);
        mTabUser = (LinearLayout) this.findViewById(R.id.ll_tab_user);

        //imgb
        mImgbWeixin = (ImageButton) this.findViewById(R.id.imgb_tab_weixin);
        mImgbContact = (ImageButton) this.findViewById(R.id.imgb_tab_contact);
        mImgbFind = (ImageButton) this.findViewById(R.id.imgb_tab_find);
        mImgbUser = (ImageButton) this.findViewById(R.id.imgb_tab_user);
    }


    @Override
    public void onClick(View v) {
        //重置圖片
        resetImgb();

        //1.點亮對應按鈕
        //2.切換到對應frgment上
        switch (v.getId()) {
            case R.id.ll_tab_weixin:
                setSelect(0);
                break;
            case R.id.ll_tab_contact:
                setSelect(1);
                break;
            case R.id.ll_tab_find:
                setSelect(2);
                break;
            case R.id.ll_tab_user:
                setSelect(3);
                break;

            default:
                break;
        }
    }

    public void setSelect(int select) {
        //1.點亮對應按鈕
        //2.切換到對應frgment上


        //fragment管理器類
        FragmentManager fm = this.getFragmentManager();
        //開啟管理器事務
        FragmentTransaction transaction = fm.beginTransaction();

        //隱藏
        hideFragment(transaction);

        switch (select) {
            case 0:
                if (mFrgWeixin == null) {
                    mFrgWeixin = new WeixinFragment();
                    transaction.add(R.id.id_content, mFrgWeixin);
                } else {
                    transaction.show(mFrgWeixin);
                }
                mImgbWeixin.setImageResource(R.drawable.weixinon);

                break;

            case 1:
                if (mFrgContact == null) {
                    mFrgContact = new ContactFragment();
                    transaction.add(R.id.id_content, mFrgContact);
                } else {
                    transaction.show(mFrgContact);
                }
                mImgbContact.setImageResource(R.drawable.contacton);

                break;

            case 2:
                if (mFrgFind == null) {
                    mFrgFind = new FindFragment();
                    transaction.add(R.id.id_content, mFrgFind);
                } else {
                    transaction.show(mFrgFind);
                }
                mImgbFind.setImageResource(R.drawable.findon);

                break;

            case 3:
                if (mFrgUser == null) {
                    mFrgUser = new UserFragment();
                    transaction.add(R.id.id_content, mFrgUser);
                } else {
                    transaction.show(mFrgUser);
                }
                mImgbUser.setImageResource(R.drawable.useron);

                break;

            default:
                break;
        }
        transaction.commit();
    }

    private void hideFragment(FragmentTransaction transaction) {
        if (mFrgWeixin != null) {
            transaction.hide(mFrgWeixin);
        }
        if (mFrgContact != null) {
            transaction.hide(mFrgContact);
        }
        if (mFrgFind != null) {
            transaction.hide(mFrgFind);
        }
        if (mFrgUser != null) {
            transaction.hide(mFrgUser);
        }
    }
}

 

(2)WeixinFragment(首頁,附帶ListView)

 

public class WeixinFragment extends Fragment implements AdapterView.OnItemClickListener {

    private ListView mListView;
    private LvAdapter mAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //反射布局
        View view = inflater.inflate(R.layout.fragment_weixin, container, false);
        //反射控件
        mListView = (ListView) view.findViewById(R.id.lv_1);

        //調用適配器
        mAdapter = new LvAdapter(getActivity());
        //適配器關聯控件
        mListView.setAdapter(mAdapter);
        //適配器關聯數據
        mAdapter.setList(Utils.getAppList(getActivity()));
        mAdapter.notifyDataSetChanged();

        //聲明事件
        mListView.setOnItemClickListener(this);

        return view;
    }


    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {

        Intent intent = new Intent();
        intent.setClass(getActivity(), DialogActivity.class);

        //1.得到item
        HashMap map = (HashMap) parent.getItemAtPosition(position);
        //2.得到item的內容
        String tv_name = (String) map.get("tv_name");
        //3.傳值
        intent.putExtra("tv_name", tv_name);
        startActivity(intent);
    }
}


 

(3)Adapter

 

public class LvAdapter extends BaseAdapter {
    private List> mList;
    private LayoutInflater mLayoutInflater;

    public LvAdapter(Context context) {
        mLayoutInflater = LayoutInflater.from(context);
    }

    public void setList(List> dataList) {
        this.mList = dataList;
    }

    @Override
    public int getCount() {
        return (mList == null) ? 0 : mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            //反射布局
            convertView = mLayoutInflater.inflate(R.layout.item_listview, null);
            //反射控件
            holder.iv_logo = (ImageView) convertView.findViewById(R.id.iv_logo);
            holder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            holder.tv_version = (TextView) convertView.findViewById(R.id.tv_version);
            holder.tv_time = (TextView) convertView.findViewById(R.id.tv_time);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        //賦值
        Map map = mList.get(position);
        holder.iv_logo.setImageDrawable((android.graphics.drawable.Drawable) mList.get(position).get("iv_logo"));

        holder.tv_name.setText((String) map.get("tv_name"));
        holder.tv_version.setText((String) map.get("tv_version"));
        holder.tv_time.setText((String) map.get("tv_time"));

        return convertView;
    }

    public class ViewHolder {
        ImageView iv_logo;
        TextView tv_name;
        TextView tv_version;
        TextView tv_time;
    }
}

 

(4)Utils

 

public class Utils {
    public static List> getAppList(Context context) {
        List> list = new ArrayList>();
        //包管理器
        PackageManager pm = context.getPackageManager();
        //包信息集合
        List pList = pm.getInstalledPackages(0);

        for (PackageInfo packageInfo : pList) {
            Map map = new HashMap();
            map.put("iv_logo", packageInfo.applicationInfo.loadIcon(pm));
            map.put("tv_name", (String) packageInfo.applicationInfo.loadLabel(pm));
            map.put("tv_version", packageInfo.versionName);
            map.put("tv_time", getTime(packageInfo.firstInstallTime));
            list.add(map);
        }
        return list;
    }

    public static String getTime(long millis) {
        Date date = new Date(millis);
        SimpleDateFormat smf = new SimpleDateFormat("MM-dd");
        return smf.format(date);

    }
}

 

(5)DialogActivity

 

public class DialogActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dialog);

        TextView tv_name_dialog  = (TextView) this.findViewById(R.id.tv_name_dialog);
        String tv_name = getIntent().getStringExtra("tv_name");
        tv_name_dialog.setText(tv_name);
    }
}

 

三.注意事項
1.getActivity()的使用
在自定義的Fragment裡,經常要用到getActivity()方法.例如:用匿名內部類的方式監聽到按鈕點擊事件,並用Toast輸出,第一個參數要寫getActivity(),原因如下:
對源碼進行分析:
Fragment類有getActivity()方法:

/**
 * Return the Activity this fragment is currently associated with.
 */
final public Activity getActivity() {
    return mActivity;
}
而其中的mActivity是:
 // Activity this fragment is attached to.
    Activity mActivity;
即,當前fragment所綁定的Activity.
同理可知,在fragment中用setAdapter(mAdapter);intent.setClass(getActivity(),DialogActivity.class);等等方法傳參時,注意不要同MainActivity一樣使用this了,而是要用getActivity().

 


2.XML中引入fragment布局
(1)直接引入:


    android:layout_width="fill_parent"
    android:layout_height="45dp"
    />
(2)用標簽引入

3.fragment中的ListView
fragment 中使用 ListView 時,ListView及適配器的調用要寫在onCreateView()方法中.

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved