原创

Android社交系统----代码结构

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://twjitm.blog.csdn.net/article/details/51841690

今天终于考完了!也该来把这篇博客写完!不能留下空白!上一篇博客主要是介绍这个社交系统的界面和一下功能了!现在我们来看看怎么实现这些界面或功能的!
首先:我们来看看项目 的目录吧,这个项目是在myeclipse环境下开发的,这里写图片描述
正如图片中所看到的。按照不同的功能将代码进行这样的分包,好吧,这是我学Android以来一直的分包习惯,任何Android程序都又代码一步一步的实现的,若是我每个部分的代码都说一遍的话可能长篇大论,我就跳几个有意义的代码来说说,要是想要源码的小伙伴,后面提供下载
首先来看看登录模块

package com.xl.activity;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.example.xl.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xl.entity.User;
import com.xl.service.UserService;
import com.xl.util.ConservationDataUtil;
import com.xl.util.IsMobileUtil;
import com.xl.util.MD5Encoder;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends FragmentActivity implements OnClickListener{
    private  EditText            fist_login_uname,
    login_psw;  //用户登录名称和密码
    SharedPreferences.Editor     shareuserdatafromid;    //用来存放用户的ID
    SharedPreferences.Editor     shareuserdatafromiphone;//手机登录保存数据
    private IsMobileUtil isMobileUtil;
    ProgressDialog       progressDialog = null;//进度弹框
    private TextView             titleBarRightStr;
    @ViewInject(R.id.title_textview)
    private TextView title_textview;
    @ViewInject(R.id.forget_psw)
    private TextView forget_psw;
    @ViewInject(R.id.getpass)
    private RadioButton getpass;
    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setContentView(R.layout.fragment_login_layout);
        ViewUtils.inject(this);
        forget_psw.setOnClickListener(this);
        title_textview.setText("登录心路");
        titleBarRightStr=(TextView) findViewById(R.id.titleBarRightStr);
        titleBarRightStr.setVisibility(View.VISIBLE);
        titleBarRightStr.setText("注册");
        titleBarRightStr.setOnClickListener(this);
        shareuserdatafromid=getSharedPreferences("uid", 0).edit();
        shareuserdatafromiphone = getSharedPreferences("persondataiphone", 0).edit();
        findViewById(R.id.login_btn).setOnClickListener(this);
    }
    /**
     * 电话号码登录入口
     */
    private void loginIphone() {
        isMobileUtil=new IsMobileUtil();
        fist_login_uname=(EditText) findViewById(R.id.fist_login_uname);
        login_psw=(EditText) findViewById(R.id.login_psw);
        Log.i("login_psw.getText().length",""+login_psw.getText().length());
        if ((null==fist_login_uname.getText().toString())&&(null==login_psw.getText().toString())) {    
            Message message=new Message();
            message.what=100;
            handler.sendMessage(message);//账号或密码为空
        }
        else if (!isMobileUtil.isMobile(fist_login_uname.getText().toString().trim())){
            Message message=new Message();//账号错误
            message.what=101;
            handler.sendMessage(message);
        }else if (login_psw.getText().length()<6){
            //密码不正确
            Message message=new Message();
            message.what=102;
            handler.sendMessage(message);
        }else {
            postDatawebservice();
        }
    }
    /**
     * 提交数据
     * @param i
     */
    private void postDatawebservice() {

        progressDialog = ProgressDialog.show(this, "登录中...", "获取数据中...", true);
        ExecutorService executorService=Executors.newFixedThreadPool(2);
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                UserService userService=new UserService();
                try {
                    User tUser= userService.login(fist_login_uname.getText().toString().trim(),
                         MD5Encoder.encode(login_psw.getText().toString()).substring(0, 10));
                    shareuserdatafromid.clear();
                    shareuserdatafromid.putInt("UId", tUser.getUId());
                    shareuserdatafromid.commit();
                    ConservationDataUtil conservationDataUtil=new ConservationDataUtil();
                    conservationDataUtil.conservationdata(shareuserdatafromiphone,tUser);
                    Intent intent_ok=new Intent();
                    intent_ok.setClass(getApplicationContext(), MainActivity.class);
                    startActivity(intent_ok);
                    finish();//关闭当前activity

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                progressDialog.dismiss();
            }
        });
    }

    @SuppressLint("HandlerLeak")
    Handler handler=new Handler(){
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            case 0:
                Toast.makeText(getApplicationContext(), "出错", Toast.LENGTH_LONG).show();
                break;
            case 1:
                Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_LONG).show();
                break;
            case 2:
                Toast.makeText(getApplicationContext(), "账号不存在", Toast.LENGTH_LONG).show();
                break;
            case 3:
                Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_LONG).show();
                break;
            case 4:
                Toast.makeText(getApplicationContext(), "账号可能密码泄露,建议修改", Toast.LENGTH_LONG).show();
                break;

            case 100:
                Toast.makeText(getApplicationContext(), "账号或密码不能为空", Toast.LENGTH_LONG).show();
                break;
            case 101:
                Toast.makeText(getApplicationContext(), "请输入正确的账号或密码", Toast.LENGTH_LONG).show();
                break;
            case 102:
                Toast.makeText(getApplicationContext(), "密码错误", Toast.LENGTH_LONG).show();
                break;
            default:
                break;
            }
        };
    };
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.login_btn:
            loginIphone();
            break;
        case R.id.titleBarRightStr:
            Intent intent=new Intent();
            intent.setClass(getApplicationContext(), RegistActivity.class);
            startActivity(intent);
            break;
            case R.id.forget_psw:
                Intent intent1=new Intent();
                intent1.setClass(getApplicationContext(), ForgetPsdActivity.class);
                startActivity(intent1);
                break;
        default:
            break;
        }       
    }
}

通过登录页我们可以看到采用异步消息机制,在控件注解的地方用的是xutil,这样可以节省开发时间!
下面来看看主界面

package com.xl.activity;

import com.example.xl.R;
import com.xl.fragment.HomeFragment;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
    private String              TAG1="HOME";
    public static String LOCATION_BCR = "location_bcr";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //根据唯一性标识获得MenuFragment对象
        HomeFragment homeFragment=new HomeFragment();
        //开启事物管理器
        getSupportFragmentManager().
        beginTransaction().
        replace
        (R.id.content_frame, 
                homeFragment,
                TAG1).commit();
    }
    private long firstTime;
    @Override
    public void onBackPressed() {

        if (System.currentTimeMillis() - firstTime < 3000) {
            finish();
        } else {
            firstTime = System.currentTimeMillis();
            Toast.makeText(this, "连续按两次退出程序", Toast.LENGTH_LONG).show();
        }
    }

}

主界面提供2个功能,开启freagment和控制返回按钮,
下面就是重要的fragment了,在上面开启四个viewpager,这样功能样的代码就可以抽取了,提高代码的复用。

package com.xl.fragment;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.example.xl.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xl.base.BaseFragment;
import com.xl.base.BasePager;
import com.xl.pager.MainCounterPager;
import com.xl.pager.SecectCounterPager;
import com.xl.pager.SettingCounterPager;
import com.xl.pager.TaskCounterPager;
import com.xl.ui.LazyViewPager.OnPageChangeListener;
import com.xl.ui.MyViewPager;

public class HomeFragment extends BaseFragment {

    private List<BasePager>   pagelist;
                              @ViewInject(R.id.main_radio)
    private RadioGroup        main_radio;
                              @ViewInject(R.id.layout_content)//解决预加载的基类pager页面,是一个自定义控件
    private  MyViewPager      layout_content;
    private MyViewPagerAdapter myviewpageradapt;
    @Override
    public View initView() {
        /**
         * 主页  R.layout.frag_home上面有点击按钮切换布局
         */
        view=View.inflate(context, R.layout.fragement_home, null);
        ViewUtils.inject(this,view);
        return view;
    }
    @SuppressLint("NewApi")
    @Override
    public void initData() {
        //vp_content_fragment.setAdapter(arg0);
        pagelist=new ArrayList<BasePager>();
        //在添加前一定要先调用clear()方法
        pagelist.clear();
        //添加四个个界面
        pagelist.add(new MainCounterPager(getActivity()));
        pagelist.add(new SecectCounterPager(getActivity()));
        pagelist.add(new SettingCounterPager(getActivity()));
        pagelist.add(new TaskCounterPager(getActivity()));
    if (null==myviewpageradapt) {
        myviewpageradapt=new MyViewPagerAdapter();

        layout_content.setAdapter(myviewpageradapt);
    }else {
        myviewpageradapt.notifyDataSetChanged();
    }   
        main_radio.check(R.id.rb_content_fragment_home);
        main_radio.callOnClick();
        pagelist.get(0).getROOView();
        //上方页面切换效果
        //默认选中第一个个人界面
        layout_content.setCurrentItem(0);
        pagelist.get(0).initDate();

        //这个是底部按钮改变页的改变方法
        layout_content.setOnPageChangeListener(new OnPageChangeListener() {     
            @Override
            public void onPageSelected(int position) {
                // 选中某一个界面的 时候,调用当前界面对象上的initData方法调用获取数据
                pagelist.get(position).initDate();
            }       
            @Override
            public void onPageScrolled(int position, float positionOffset,
                    int positionOffsetPixels) {     
            }   
            @Override
            public void onPageScrollStateChanged(int state) {
                // TODO Auto-generated method stub      
            }
        });

        //点击下面的单选框切换效果
        main_radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                case R.id.rb_content_fragment_home:
                    layout_content.setCurrentItem(0);
                    break;
                case R.id.rb_content_fragment_shunshou:
                    layout_content.setCurrentItem(1);
                    break;

                case R.id.rb_content_fragment_xiu:
                    layout_content.setCurrentItem(2);
                    break;
                case R.id.rb_content_fragment_quan:
                    layout_content.setCurrentItem(3);
                    break;

                }
            }
        });


    }

    //点击底部切换pager的适配器


    class MyViewPagerAdapter extends PagerAdapter{

        @Override
        public int getCount() {
            return pagelist.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            // TODO Auto-generated method stub
            return arg0==arg1;
        }
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(pagelist.get(position).getROOView());
            return pagelist.get(position).getROOView();
        }
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View)object);
        }
    }
}

而后对于不同的viewpager页面有自己不用的布局,
发布页的代码

package com.xl.pager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ToggleButton;

import com.example.xl.R;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.http.client.entity.UploadEntity;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xl.adapter.TaskSpinnerAdapter;
import com.xl.aip.MyApplication;
import com.xl.base.BasePager;
import com.xl.entity.Task;
import com.xl.service.TaskService;
import com.xl.util.FormatDateUtil;

public class MainCounterPager extends BasePager implements OnClickListener{
    private SharedPreferences settingsiphone,settingsid;
    SharedPreferences.Editor  shareuserdatafromiphone;
    @ViewInject(R.id.title_textview)
    private TextView         title_textview;//标题文字
    @ViewInject(R.id.task_type)
    private Spinner task_type;//心情类别
    @ViewInject(R.id.edit_content)
    private EditText edit_content;//心情输入类容
    @ViewInject(R.id.end_time)    //心情时间
    private TextView end_time;
    @ViewInject(R.id.text_didian)
    private TextView text_didian;//心情发布地点
    private String feeltype="美好";
    @ViewInject(R.id.upload_btn)
    private Button upload_btn;
    @ViewInject(R.id.mTogBtn)
    private ToggleButton mTogBtn;
    private ExecutorService executorService;
    public static String TAG = "LocTestDemo";
    private BroadcastReceiver broadcastReceiver;
    public static String LOCATION_BCR = "location_bcr";
    ProgressDialog       progressDialog = null;//进度弹框
    private int TogBtnstat=0;//可见吗?
    public MainCounterPager(Context context) {
        super(context);
    }
    @Override
    public View initView() {
        view=View.inflate(context, R.layout.activity_selectimg, null);
        ViewUtils.inject(this,view);
        end_time.setOnClickListener(this);
        text_didian.setOnClickListener(this);
        upload_btn.setOnClickListener(this);
        mTogBtn.setOnCheckedChangeListener(new OnCheckedChangeListener() {  

            @Override  
            public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {  
                // TODO Auto-generated method stub  
                if(isChecked){  
                    //选中  
                    TogBtnstat=0;
                    mTogBtn.setText("可见");
                }else{  
                    //未选中  
                    TogBtnstat=1;
                    mTogBtn.setTag("不可见");
                }  
            }  
        });// 添加监听事件  );
        return view;
    }
    @Override
    public void initDate() {
        settingsiphone=context.getSharedPreferences("persondataiphone", 0);

        executorService=Executors.newFixedThreadPool(3);
        title_textview.setText("发布心情");
        final List<String>spinnerList=getTaskTypeData();
        task_type.setAdapter(new TaskSpinnerAdapter(spinnerList,context));
        task_type.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                Toast.makeText(context, spinnerList.get(arg2)+"",Toast.LENGTH_LONG).show();
                feeltype=spinnerList.get(arg2);
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
            }
        });

        initialize();   
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        //发布心情
        case R.id.upload_btn:
            UploadTaskToNet();
            break;
            //获取发布时间
        case R.id.end_time:
            end_time .setText(getTaskTime(1));
            break;
            //获取发布地点
        case R.id.text_didian:
            text_didian.setText("定位中...");
            MyApplication.getInstance().requestLocationInfo();
            break;
        default:
            break;
        }
    }   
    /**
     * 获取发布时间
     * @return
     */
    private String getTaskTime(int i) {
        Date taDate=new Date();
        FormatDateUtil util=new FormatDateUtil();
        if (i==0) {
            String stringdate=util.setFromatDate(taDate);
            return stringdate;  
        }else {
            String stringdate=util.setFromatDateViewLoca(taDate);
            return stringdate;  
        }

    }
    /**
     * 发布心情
     */
    private void UploadTaskToNet() {
        progressDialog = ProgressDialog.show(context, "提交中...", "提交数据中...", true);
        executorService.execute(new Runnable() {
            @Override
            public void run() { 
                TaskService taskService=new TaskService();
                Task task=getDataFromUI();
                taskService.Save(task);
                progressDialog.dismiss();
                Message message=Message.obtain();
                message.what=0X00;
                handler.sendMessage(message);
            }
        });

    }
    @SuppressLint("HandlerLeak")
    Handler handler =new Handler(){

        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
            //发布成功后清除页面数据
            case 0X00:
                edit_content.setText("");
                Toast.makeText(context, "发布心情成功~", Toast.LENGTH_LONG).show();
                break;

            default:
                break;
            }
        };
    };
    /**
     * 从前台获取心情数据数据
     * @return
     */
    private Task getDataFromUI() {
        Task task=new Task();
        String position= text_didian.getText().toString();
        if ("".equals(position)) {
            position="no position";
        }
        String conteString= edit_content.getText().toString();
        if ("".equals(conteString)) {
            conteString="今天好心情";
        }
        task.setProperty(1, settingsiphone.getInt("UId", 0));//
        task.setProperty(2, conteString);
        task.setProperty(3, feeltype);
        task.setProperty(4, getTaskTime(0));
        task.setProperty(5, "无图片");
        task.setProperty(6, position);
        task.setProperty(7,TogBtnstat);//可见性
        return task;
    }
    private List<String> getTaskTypeData() {
        List<String>list=new ArrayList<>();
        list.add("安静");
        list.add("伤感");
        list.add("快乐");
        list.add("心痛");
        list.add("励志");
        list.add("甜蜜");
        list.add("孤单");
        list.add("自愈");
        list.add("宣泄");
        list.add("叛逆");
        list.add("期待");
        return list;
    }

    private void initialize(){
        registerBroadCastReceiver();
    }
    /**
     * 获取地理位置
     */
    private void registerBroadCastReceiver() {
        broadcastReceiver = new BroadcastReceiver(){    
            @Override
            public void onReceive(Context context, Intent intent) {
                String address = intent.getStringExtra("address");
                text_didian.setText(address);               
            }
        };  
        IntentFilter intentToReceiveFilter = new IntentFilter();
        intentToReceiveFilter.addAction(LOCATION_BCR);
        context.registerReceiver(broadcastReceiver, intentToReceiveFilter);     
    }
}

。。。。。。。。后面还有一些了
其实代码还是比较好写的,在这里就不一一介绍了。点击这可以下载源码

文章最后发布于: 2016-07-06 19:07:07
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览