Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 谷歌市場Day1

谷歌市場Day1

編輯:關於Android編程

准備階段

將WebInfos文件夾放在手機存儲卡的根目錄下,用Eclipse導入項目WebSerser,運行到手機中。

將WebInfos文件夾放在手機存儲卡的根目錄下

用ADB命令 adb push將WebInfos文件夾中的而所有文件推送到手機存儲卡的WebInfos文件夾中。命令的使用詳看:Android基礎:ADB

WebInfos下載地址

運行WebSerser

用Eclipse導入WebSerser後,run運行到實際中,開啟服務即可。

這裡寫圖片描述
WebSerser下載地址

需要依賴包:android-support-v7-appcompat

點擊下載 android-support-v7-appcompat

開始寫代碼

Step1:分包

圖一:
這裡寫圖片描述

Step2: 准備工具類

MyApplication 獲取全局使用的Context + 獲取全局使用的handler LogUtil ToastUtil.java

MyApplication

記得在AndroidManifest.xml配置application

public class MyApplication extends Application {

    private static Context context;
    private static Handler mainHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        mainHandler = new Handler();
    }

    /**
     * 獲取全局使用的Context
     * @return
     */
    public static Context getContext() {
        return context;
    }

    /**
     * 獲取全局使用的handler
     * @return
     */
    public static Handler getMainHandler() {
        return mainHandler;
    }
}

LogUtil.java

public class LogUtil {

    private static boolean isDebug = true;

    public static void d(String TAG, String content) {
        if (isDebug) {
            Log.d(TAG, content);
        }
    }
}

ToastUtil.java

public class ToastUtil {

    private static Toast toast;
    /**
     * 短吐司
     * @param context
     * @param text
     */
    public static void showShortToast(Context context, String text) {
        if (toast == null) {
            toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
        }
        toast.setText(text);
        toast.show();
    }
    /**
     * 長吐司
     * @param context
     * @param text
     */
    public static void showLongToast(Context context, String text) {
        if (toast == null) {
            toast = Toast.makeText(context, text, Toast.LENGTH_LONG);
        }
        toast.setText(text);
        toast.show();
    }

    /**
     * 短吐司
     * @param text
     */
    public static void showShortToast(String text) {
        if (toast == null) {
            toast = Toast.makeText(MyApplication.getContext(), text,
                    Toast.LENGTH_SHORT);
        }
        toast.setText(text);
        toast.show();
    }

    /**
     * 長吐司
     * @param text
     */
    public static void showLongToast(String text) {
        if (toast == null) {
            toast = Toast.makeText(MyApplication.getContext(), text,
                    Toast.LENGTH_LONG);
        }
        toast.setText(text);
        toast.show();
    }
}

Step3:實現側拉效果

效果圖:
這裡寫圖片描述

側拉效果實在MainActivity.java中設置的。

布局:activity_main.xml


    
    

    

        <frameLayout
            android:id="@+id/frame_home"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        </frameLayout>
    
    

    

        
    

布局:menu_list.xml

圖:
這裡寫圖片描述




    

        

        

            

            

            

                

                
            
        
        

        
        

        

            

            
        

        
        

        

            

            
        

        
        

        

            

            
        

        
        

        

            

            
        

        
        

        

            

            
        

        
        

        

            

            
        

        
        

        

            

            
        

        
        

        

            

            
        

        
    

代碼:MainActivity

public class MainActivity extends ActionBarActivity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }

    private void initViews() {
        initActionBar();
        initDrawerLayout();
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setIcon(R.drawable.ic_launcher);//設置home圖標
        actionBar.setDisplayShowHomeEnabled(true);//顯示home圖標
        actionBar.setHomeButtonEnabled(true);//home圖標可點擊
        actionBar.setDisplayHomeAsUpEnabled(true);//顯示導航圖標
    }

    private void initDrawerLayout() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        //創建監聽對(ActionBarDrawerToggle 實現了DrawerLayout.DrawerListener),添加導航圖標
        toggle = new ActionBarDrawerToggle(this, drawerLayout,R.drawable.ic_drawer_am, 0, 0);
        toggle.syncState();// 少了這一行,ic_drawer_am就是默認的圖標,不是我們指定的。
        drawerLayout.setDrawerListener(toggle);
    }

    /**
     * 要想側欄欄出現,還要加這一行代碼:toggle.onOptionsItemSelected(item);
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        toggle.onOptionsItemSelected(item);
        return super.onOptionsItemSelected(item);
    }
}

Step4:實現側拉欄和內容頁的聯動

點擊側拉欄item,內容頁顯示不同的內容。

邏輯:每一個item對應一個fragment,點擊item,先隱藏所有的fragment,再顯示該item對應的fragment,如果fragment為null,則創建它。

MainActivity.java

public class MainActivity extends ActionBarActivity implements OnClickListener {

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle toggle;
    private RelativeLayout home_layout;
    private RelativeLayout setting_layout;
    private RelativeLayout theme_layout;
    private RelativeLayout scans_layout;
    private RelativeLayout feedback_layout;
    private RelativeLayout updates_layout;
    private RelativeLayout about_layout;
    private RelativeLayout exit_layout;
    private FrameLayout frame_home;
    private FragmentManager fm;
    private HomeFragment homeFrag;
    private SettingFragment setFrag;
    private ThemeFragment themeFrag;
    private ScanFragment scanFrag;
    private UpdateFragment updateFrag;
    private AboutFragment aboutFrag;
    private ExitFragment exitFragment;

    private FragmentTransaction transaction;
    private TextView tv_home;
    private TextView tv_setting;
    private TextView tv_theme;
    private TextView tv_scans;
    private TextView tv_feedback;
    private TextView tv_updates;
    private TextView tv_about;
    private TextView tv_exit;
    private FeedBackFragment feedBackFrag;

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

    private void initViews() {
        initActionBar();
        initDrawerLayout();
        findMenuViews();
        initMenuView();
        home_layout.performClick();
    }

    private void initMenuView() {
        fm = getSupportFragmentManager();
        home_layout.setOnClickListener(this);
        setting_layout.setOnClickListener(this);
        theme_layout.setOnClickListener(this);
        scans_layout.setOnClickListener(this);
        feedback_layout.setOnClickListener(this);
        updates_layout.setOnClickListener(this);
        about_layout.setOnClickListener(this);
        exit_layout.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        setAllFalse();
        transaction = fm.beginTransaction();
        hideAllFragment();//先創建FragmentTransaction對象,在隱藏
        switch (v.getId()) {
        case R.id.home_layout:
            tv_home.setSelected(true);
            if (homeFrag == null) {
                homeFrag = new HomeFragment();
                transaction.add(R.id.frame_home, homeFrag, "HomeFragment");
            }
            transaction.show(homeFrag);
            break;
        case R.id.setting_layout:
            tv_setting.setSelected(true);
            if (setFrag == null) {
                setFrag = new SettingFragment();
                transaction.add(R.id.frame_home, setFrag, "SettingFragment");
            }
            transaction.show(setFrag);
            break;
        case R.id.theme_layout:
            tv_theme.setSelected(true);
            if (themeFrag == null) {
                themeFrag = new ThemeFragment();
                transaction.add(R.id.frame_home, themeFrag, "ThemeFragment");
            }
            transaction.show(themeFrag);
            break;
        case R.id.scans_layout:
            tv_scans.setSelected(true);
            if (scanFrag == null) {
                scanFrag = new ScanFragment();
                transaction.add(R.id.frame_home, scanFrag, "ScanFragment");
            }
            transaction.show(scanFrag);
            break;
        case R.id.feedback_layout:
            tv_feedback.setSelected(true);
            if (feedBackFrag == null) {
                feedBackFrag = new FeedBackFragment();
                transaction.add(R.id.frame_home, feedBackFrag, "FeedBackFragment");
            }
            transaction.show(feedBackFrag);
            break;
        case R.id.updates_layout:
            tv_updates.setSelected(true);
            if (updateFrag == null) {
                updateFrag = new UpdateFragment();
                transaction.add(R.id.frame_home, updateFrag, "UpdateFragment");
            }
            transaction.show(updateFrag);
            break;
        case R.id.about_layout:
            tv_about.setSelected(true);
            if (aboutFrag == null) {
                aboutFrag = new AboutFragment();
                transaction.add(R.id.frame_home, aboutFrag, "AboutFragment");
            }
            transaction.show(aboutFrag);
            break;
        case R.id.exit_layout:
            tv_exit.setSelected(true);
            if (exitFragment == null) {
                exitFragment = new ExitFragment();
                transaction.add(R.id.frame_home, exitFragment, "ExitFragment");
            }
            transaction.show(exitFragment);
            break;
        }
        drawerLayout.closeDrawers();
        transaction.commit();
    }

    private void setAllFalse() {
        tv_home.setSelected(false);
        tv_setting.setSelected(false);
        tv_theme.setSelected(false);
        tv_scans.setSelected(false);
        tv_feedback.setSelected(false);
        tv_updates.setSelected(false);
        tv_about.setSelected(false);
        tv_exit.setSelected(false);
    }

    private void hideAllFragment() {
        if (homeFrag != null) {
            transaction.hide(homeFrag);
        }
        if (setFrag != null) {
            transaction.hide(setFrag);
        }
        if (themeFrag != null) {
            transaction.hide(themeFrag);
        }
        if (scanFrag != null) {
            transaction.hide(scanFrag);
        }
        if (feedBackFrag != null) {
            transaction.hide(feedBackFrag);
        }
        if (updateFrag != null) {
            transaction.hide(updateFrag);
        }
        if (aboutFrag != null) {
            transaction.hide(aboutFrag);
        }
        if (exitFragment != null) {
            transaction.hide(exitFragment);
        }
    }

    private void findMenuViews() {
        frame_home = (FrameLayout) findViewById(R.id.frame_home);
        home_layout = (RelativeLayout) findViewById(R.id.home_layout);
        setting_layout = (RelativeLayout) findViewById(R.id.setting_layout);
        theme_layout = (RelativeLayout) findViewById(R.id.theme_layout);
        scans_layout = (RelativeLayout) findViewById(R.id.scans_layout);
        feedback_layout = (RelativeLayout) findViewById(R.id.feedback_layout);
        updates_layout = (RelativeLayout) findViewById(R.id.updates_layout);
        about_layout = (RelativeLayout) findViewById(R.id.about_layout);
        exit_layout = (RelativeLayout) findViewById(R.id.exit_layout);

        tv_home = (TextView) findViewById(R.id.tv_home);
        tv_setting = (TextView) findViewById(R.id.tv_setting);
        tv_theme = (TextView) findViewById(R.id.tv_theme);
        tv_scans = (TextView) findViewById(R.id.tv_scans);
        tv_feedback = (TextView) findViewById(R.id.tv_feedback);
        tv_updates = (TextView) findViewById(R.id.tv_updates);
        tv_about = (TextView) findViewById(R.id.tv_about);
        tv_exit = (TextView) findViewById(R.id.tv_exit);
    }

    private void initActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setIcon(R.drawable.ic_launcher);//設置home圖標
        actionBar.setDisplayShowHomeEnabled(true);//顯示home圖標
        actionBar.setHomeButtonEnabled(true);//home圖標可點擊
        actionBar.setDisplayHomeAsUpEnabled(true);//顯示導航圖標
    }

    private void initDrawerLayout() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        //創建監聽對(ActionBarDrawerToggle 實現了DrawerLayout.DrawerListener),添加導航圖標
        toggle = new ActionBarDrawerToggle(this, drawerLayout,R.drawable.ic_drawer_am, 0, 0);
        toggle.syncState();// 少了這一行,ic_drawer_am就是默認的圖標,不是我們指定的。
        drawerLayout.setDrawerListener(toggle);
    }

    /**
     * 要想側欄欄出現,還要加這一行代碼:toggle.onOptionsItemSelected(item);
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        toggle.onOptionsItemSelected(item);
        return super.onOptionsItemSelected(item);
    }
}

Step5:實現側拉欄“首頁”對應的界面

HomeFragment.java

HomeFragmentAdapter很簡單,不在復制

public class HomeFragment extends Fragment {

    private View rootView;
    private PagerSlidingTab indicatorTab;
    private ViewPager viewPager;
    private HomeFragmentAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_home, container, false);
        indicatorTab = (PagerSlidingTab) rootView.findViewById(R.id.indicatorTab_frag_home);
        viewPager = (ViewPager) rootView.findViewById(R.id.viewPager_frag_home);
        viewPager.setOffscreenPageLimit(CommonUtil.getStringArray(R.array.tab_names).length-1);
        adapter = new HomeFragmentAdapter(getActivity().getSupportFragmentManager());
        viewPager.setAdapter(adapter);
        indicatorTab.setViewPager(viewPager);
        return rootView;
    }
}

fragment_home.xml

PagerSlidingTab是自定義的tab類,copy即可,即下圖:

這裡寫圖片描述




    
    

    

Step6:ContentPager.java

ContentPager這個類非常重要,包含4中View:加載中頁面 + 加載成功頁面 + 加載失敗頁面 + 數據為null的頁面

package com.cqc.googleplay.view;

import java.util.List;

import com.cqc.googleplay.R;
import com.cqc.googleplay.application.MyApplication;
import com.cqc.googleplay.utils.CommonUtil;

import android.content.Context;
import android.os.SystemClock;
import android.provider.Settings.System;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

public abstract class ContentPager extends FrameLayout {

    public ContentPager(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initContentPager();
    }

    public ContentPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        // this(context, attrs, 0);
        initContentPager();
    }

    public ContentPager(Context context) {
        super(context);
        // this(context,null);
        initContentPager();
    }

    private void initContentPager() {
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT);
        if (loadingView == null) {
            loadingView = View.inflate(MyApplication.getContext(),
                    R.layout.page_loading, null);
        }
        addView(loadingView);

        if (emptyView == null) {
            emptyView = View.inflate(MyApplication.getContext(),
                    R.layout.page_empty, null);
        }
        addView(emptyView);

        if (errorView == null) {
            errorView = View.inflate(MyApplication.getContext(),
                    R.layout.page_error, null);
        }
        addView(errorView);

        if (successView == null) {
            successView = createSuccessView();
        }
        addView(successView);

        // 根據狀態顯示view
        showPager();

        // 加載數據
        loadDataAndRefresh();
    }

    /**
     * 請求數據並更新頁面
     */
    private void loadDataAndRefresh() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                // 請求數據
                SystemClock.sleep(1500);
                Object object = requestData();
                mState = checkData(object);
                // 顯示數據,主線程運行
                CommonUtil.runOnUIThread(new Runnable() {
                    @Override
                    public void run() {
                        showPager();
                    }
                });
            }
        }.start();
    }

    protected PagerState checkData(Object object) {
        if (object == null) {
            mState = PagerState.STATE_ERROR;
        } else {
            if (object instanceof List) {
                if (((List) object).size() == 0) {
                    mState = PagerState.STATE_EMPTY;
                } else {
                    mState = PagerState.STATE_SUCCESS;
                }
                mState = PagerState.STATE_SUCCESS;
            } else {
                mState = PagerState.STATE_SUCCESS;
            }
        }
        return mState;
    }


    private void showPager() {
        hideAllView();
        switch (mState.getValue()) {
        case 1:
            loadingView.setVisibility(View.VISIBLE);
            break;
        case 2:
            successView.setVisibility(View.VISIBLE);
            break;
        case 3:
            emptyView.setVisibility(View.VISIBLE);
            break;
        case 4:
            errorView.setVisibility(View.VISIBLE);
            break;
        }
    }

    private void hideAllView() {
        if (loadingView != null) {
            loadingView.setVisibility(View.GONE);
        }
        if (successView != null) {
            successView.setVisibility(View.GONE);
        }
        if (emptyView != null) {
            emptyView.setVisibility(View.GONE);
        }
        if (errorView != null) {
            errorView.setVisibility(View.GONE);
        }
    }

    /**
     * 請求數據
     * @return
     */
    public abstract Object requestData();
    /**
     * 每個fragment的view不同
     * @return
     */
    public abstract View createSuccessView();

    /**
     * 定義4中加載狀態:加載中 + 加載成功 + 加載失敗 + 數據為null
     * 
     * @author cui
     */
    public enum PagerState {
        STATE_lOADIGN(1), STATE_SUCCESS(2), STATE_EMPTY(3), STATE_ERROR(4);

        private int value;

        PagerState(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

    /**
     * 4中狀態對應的view
     */
    private View loadingView;
    private View successView;
    private View emptyView;
    private View errorView;

    private PagerState mState = PagerState.STATE_lOADIGN;
}

Step7:item首頁對應的子首頁 HomeFrag.java

public class HomeFrag extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        ContentPager contentPager = new ContentPager(getActivity()) {

            @Override
            public Object requestData() {

                return "cuicui";
            }

            @Override
            public View createSuccessView() {
                TextView textView = new TextView(getContext());
                textView.setText("successView");
                return textView;
            }
        };
        return contentPager;
    }
}

源碼下載

谷歌市場第一天

遇到的坑

NullPointerException

效果圖:
這裡寫圖片描述

檢查了多遍,沒發現null的,後來發現賦值錯了。

見圖:
這裡寫圖片描述
這裡寫圖片描述

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