編輯:關於Android編程
今天終於考完了!也該來把這篇博客寫完!不能留下空白!上一篇博客主要是介紹這個社交系統的界面和一下功能了!現在我們來看看怎麼實現這些界面或功能的!
首先:我們來看看項目 的目錄吧,這個項目是在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 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();
//在添加前一定要先調用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 ListspinnerList=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 getTaskTypeData() {
Listlist=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);
}
}
。。。。。。。。後面還有一些了
其實代碼還是比較好寫的,在這裡就不一一介紹了。
內存洩露,是Android開發者最頭疼的事。可能一處小小的內存洩露,都可能是毀千裡之堤的蟻穴。 怎麼才能檢測內存洩露呢? AndroidStudio 中Memory控件台
使用MediaRecorder錄制音頻步驟: 創建MediaRecorder對象MediaRecorder recorder = new MediaRecorder()
ExpandableListView介紹 ExpandableListView的引入 ExpandableListView可以顯示一個視圖垂直滾動顯示
Activity的啟動;Intent intent = new Intent(this,A.class);startActivity(intent);startActiv