利用Android Studio快速搭建App
大家好,我是烤鴨:
給大家分享一個簡單的用Android Studio快速搭建app
工具:
?Android Studio 64位 專業(yè)版
插件:
??Datepicker Timepicker okhttp
實現(xiàn)需求:
?界面上選擇時間,發(fā)get/post請求到后臺,獲取選擇的時間。
1.修改AndroidManifest.xml文件
?其中可以修改app樣式,app圖標,進入app的最先執(zhí)行哪個activity,
最重要的!!!
創(chuàng)建的activity一定要在這里注冊。
項目名/app/build.gradle中添加依賴,這里貼一下我用到的。
apply plugin: 'com.android.application'android {compileSdkVersion 26defaultConfig {applicationId "com.example.gmwang.washapplication"minSdkVersion 15targetSdkVersion 26versionCode 1versionName "1.0"testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"}buildTypes {release {minifyEnabled falseproguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'}} }dependencies {implementation fileTree(dir: 'libs', include: ['*.jar'])implementation 'com.android.support:appcompat-v7:26.1.0'implementation 'com.android.support.constraint:constraint-layout:1.0.2'testImplementation 'junit:junit:4.12'androidTestImplementation 'com.android.support.test:runner:1.0.1'androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.7'compile 'com.squareup.okhttp3:okhttp:3.3.0'compile 'com.android.support:design:+'compile 'com.zhy:okhttputils:2.6.1'compile 'com.alibaba:fastjson:1.2.7' }2.創(chuàng)建Splash頁面
?可以看到上面我設(shè)置的最先跳轉(zhuǎn)的activity是SplashActivity,這是一個過渡頁面,一般app都是有一個頁面或者是廣告,等幾秒再進入app的首頁。
創(chuàng)建SplashActivity
package com.example.gmwang.washapplication;import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.annotation.Nullable;import java.util.Timer; import java.util.TimerTask;/*** Created by gmwang on 2017/11/15.*/public class SplashActivity extends Activity {Timer timer;Message message;private Handler handler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case 1:if (timer != null) {timer.cancel();timer = null;}Intent i = new Intent(SplashActivity.this,WashViewActivity.class);startActivity(i);break;default:break;}}};@Overrideprotected void onCreate(@Nullable Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_spalsh);timer = new Timer();timer.scheduleAtFixedRate(new TimerTask() {@Overridepublic void run() {message = new Message();message.what = 1;handler.sendMessage(message);}}, 3000, 3000);} }
先說這一行:
setContentView(R.layout.activity_spalsh);
需要創(chuàng)建activity_spalsh的layout,就是頁面。
這里就是畫了一個簡單的頁面,里邊放了一張圖。
代碼如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:background="#333333"><pl.droidsonroids.gif.GifImageViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:src="@drawable/wash"/> </LinearLayout>
再說這一行:
Intent i = new Intent(SplashActivity.this,WashViewActivity.class);
就是從這個頁面3秒之后,跳轉(zhuǎn)到哪個acticity。
3.創(chuàng)建WashViewActivity頁面
這個頁面就稍微復雜點,需要有picker插件和okhttp。
先把代碼貼出來:
package com.example.gmwang.washapplication;import android.app.Activity; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.os.Bundle; import android.support.constraint.ConstraintLayout; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast;import com.alibaba.fastjson.JSONObject; import com.example.gmwang.washapplication.utils.Constants; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback;import java.util.Calendar;import okhttp3.Call;/*** Created by gmwang on 2017/11/24.*/public class WashViewActivity extends Activity {private TextView tvShowDialog;private TextView timeDialog;private Calendar cal;private int year, month, day;private int hour, minute;private String dateString = "0000";private String timeString = "0000";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_washview);Button recordButton = findViewById(R.id.recordId);Button recordListButton = findViewById(R.id.recordList);tvShowDialog = (TextView) findViewById(R.id.tvShowDialog);timeDialog = (TextView) findViewById(R.id.timeDialog);//獲取當前日期getDate();tvShowDialog.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {switch (view.getId()) {case R.id.tvShowDialog:DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {@Overridepublic void onDateSet(DatePicker arg0, int year, int month, int day) {dateString = year + "-" + (++month) + "-" + day;tvShowDialog.setText(dateString); //將選擇的日期顯示到TextView中,因為之前獲取month直接使用,所以不需要+1,這個地方需要顯示,所以+1}};DatePickerDialog dialog = new DatePickerDialog(WashViewActivity.this, 0, listener, year, month, day);//后邊三個參數(shù)為顯示dialog時默認的日期,月份從0開始,0-11對應1-12個月dialog.show();break;default:break;}}});timeDialog.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {switch (view.getId()) {case R.id.timeDialog:TimePickerDialog.OnTimeSetListener listener = new TimePickerDialog.OnTimeSetListener() {@Overridepublic void onTimeSet(TimePicker timePicker, int hour, int minute) {timeString = hour + ":"+minute;timeDialog.setText(timeString);}};TimePickerDialog dialog = new TimePickerDialog(WashViewActivity.this, 0, listener, hour, minute,true);dialog.show();break;default:break;}}});recordButton.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {Log.e("recordButton",dateString);if(TextUtils.isEmpty(tvShowDialog.getText())){Toast.makeText(getApplicationContext(), "請先選擇日期!!!!!!", Toast.LENGTH_LONG).show();return ;}if(TextUtils.isEmpty(timeDialog.getText())){Toast.makeText(getApplicationContext(), "請先選擇時間!!!!!!", Toast.LENGTH_LONG).show();return ;}String url = Constants.url+"addRecord";StringBuffer sb = new StringBuffer();OkHttpUtils.get().url(url).addParams("cuuid","66666").addParams("washDate", dateString).addParams("washTime",timeString).build().execute(new StringCallback() {@Overridepublic void onError(Call call, Exception e, int id) {Log.e("onError:", e.toString());}@Overridepublic void onResponse(String response, int id) {Log.e("onResponse:", response);JSONObject responseJson = (JSONObject) JSONObject.parse(response);String code = responseJson.getString("code");String message = responseJson.getString("message");//保存成功if("100".equals(responseJson.get("code"))){Toast.makeText(getApplicationContext(), code+","+responseJson.get("message"), Toast.LENGTH_LONG).show();}else{Toast.makeText(getApplicationContext(), code+","+responseJson.get("message"), Toast.LENGTH_LONG).show();}}});}});}//獲取當前日期private void getDate() {cal = Calendar.getInstance();year = cal.get(Calendar.YEAR); //獲取年月日時分秒Log.i("wxy", "year" + year);month = cal.get(Calendar.MONTH); //獲取到的月份是從0開始計數(shù)day = cal.get(Calendar.DAY_OF_MONTH);hour = cal.get(Calendar.HOUR_OF_DAY);minute = cal.get(Calendar.MINUTE);} }
代碼有點多,我們一行一行看:
setContentView(R.layout.activity_washview);
跟上面一樣,去畫個頁面activity_washview去,頁面上有時間選擇插件。
效果:
3.1 activity_washview代碼:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"tools:context="com.example.gmwang.washapplication.MainActivity"><RelativeLayoutandroid:id="@+id/rle1"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="76dp"><TextViewandroid:id="@+id/dateText"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_marginLeft="10dp"android:text="日期" /><EditTextandroid:id="@+id/tvShowDialog"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:layout_toRightOf="@+id/dateText"android:background="@drawable/dateshape"android:focusable="false" /></RelativeLayout><RelativeLayoutandroid:id="@+id/r_time"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="116dp"><TextViewandroid:id="@+id/timeText"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_marginLeft="10dp"android:text="時間" /><EditTextandroid:id="@+id/timeDialog"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:layout_toRightOf="@+id/timeText"android:background="@drawable/dateshape"android:focusable="false"/></RelativeLayout><RelativeLayoutandroid:id="@+id/rle2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="156dp"></RelativeLayout><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentStart="true"android:layout_alignTop="@+id/rle1">><Buttonandroid:id="@+id/recordId"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="80dp"android:layout_marginTop="200dp"android:text="record"android:textColor="#f00"android:background="@drawable/button"/></RelativeLayout> </RelativeLayout>
3.2 貼一下自定義樣式,就是個邊框,dateshape.xml
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android"><stroke android:color="#000000"android:width="0.5dp"></stroke> </shape>
3.3 關(guān)于textview和button
定義的textview和button都是根據(jù)id來找的。
比如:
private TextView tvShowDialog;
tvShowDialog = (TextView) findViewById(R.id.tvShowDialog);
這樣就找到這個textView,就可以給他賦值或者其他操作了。button也是一樣。
3.4 時間選擇插件
DatePicker插件:
tvShowDialog.setOnClickListener 是選擇后獲取年/月/日/的
TimeDatePicker插件:
timeDialog.setOnClickListener 是選擇后獲取時/分/的
3.5 http請求
后面的按鈕點擊方法
recordButton.setOnClickListener,發(fā)送http請求,利用okhttp組件
可以看到這里的OkHttpUtils,貼一下代碼
package com.zhy.http.okhttp;import com.zhy.http.okhttp.builder.GetBuilder; import com.zhy.http.okhttp.builder.HeadBuilder; import com.zhy.http.okhttp.builder.OtherRequestBuilder; import com.zhy.http.okhttp.builder.PostFileBuilder; import com.zhy.http.okhttp.builder.PostFormBuilder; import com.zhy.http.okhttp.builder.PostStringBuilder; import com.zhy.http.okhttp.callback.Callback; import com.zhy.http.okhttp.request.RequestCall; import com.zhy.http.okhttp.utils.Platform;import java.io.IOException; import java.util.concurrent.Executor;import okhttp3.Call; import okhttp3.OkHttpClient; import okhttp3.Response;/*** Created by zhy on 15/8/17.*/ public class OkHttpUtils {public static final long DEFAULT_MILLISECONDS = 10_000L;private volatile static OkHttpUtils mInstance;private OkHttpClient mOkHttpClient;private Platform mPlatform;public OkHttpUtils(OkHttpClient okHttpClient){if (okHttpClient == null){mOkHttpClient = new OkHttpClient();} else{mOkHttpClient = okHttpClient;}mPlatform = Platform.get();}public static OkHttpUtils initClient(OkHttpClient okHttpClient){if (mInstance == null){synchronized (OkHttpUtils.class){if (mInstance == null){mInstance = new OkHttpUtils(okHttpClient);}}}return mInstance;}public static OkHttpUtils getInstance(){return initClient(null);}public Executor getDelivery(){return mPlatform.defaultCallbackExecutor();}public OkHttpClient getOkHttpClient(){return mOkHttpClient;}public static GetBuilder get(){return new GetBuilder();}public static PostStringBuilder postString(){return new PostStringBuilder();}public static PostFileBuilder postFile(){return new PostFileBuilder();}public static PostFormBuilder post(){return new PostFormBuilder();}public static OtherRequestBuilder put(){return new OtherRequestBuilder(METHOD.PUT);}public static HeadBuilder head(){return new HeadBuilder();}public static OtherRequestBuilder delete(){return new OtherRequestBuilder(METHOD.DELETE);}public static OtherRequestBuilder patch(){return new OtherRequestBuilder(METHOD.PATCH);}public void execute(final RequestCall requestCall, Callback callback){if (callback == null)callback = Callback.CALLBACK_DEFAULT;final Callback finalCallback = callback;final int id = requestCall.getOkHttpRequest().getId();requestCall.getCall().enqueue(new okhttp3.Callback(){@Overridepublic void onFailure(Call call, final IOException e){sendFailResultCallback(call, e, finalCallback, id);}@Overridepublic void onResponse(final Call call, final Response response){if (call.isCanceled()){sendFailResultCallback(call, new IOException("Canceled!"), finalCallback, id);return;}if (!finalCallback.validateReponse(response, id)){sendFailResultCallback(call, new IOException("request failed , reponse's code is : " + response.code()), finalCallback, id);return;}try{Object o = finalCallback.parseNetworkResponse(response, id);sendSuccessResultCallback(o, finalCallback, id);} catch (Exception e){sendFailResultCallback(call, e, finalCallback, id);}}});}public void sendFailResultCallback(final Call call, final Exception e, final Callback callback, final int id){if (callback == null) return;mPlatform.execute(new Runnable(){@Overridepublic void run(){callback.onError(call, e, id);callback.onAfter(id);}});}public void sendSuccessResultCallback(final Object object, final Callback callback, final int id){if (callback == null) return;mPlatform.execute(new Runnable(){@Overridepublic void run(){callback.onResponse(object, id);callback.onAfter(id);}});}public void cancelTag(Object tag){for (Call call : mOkHttpClient.dispatcher().queuedCalls()){if (tag.equals(call.request().tag())){call.cancel();}}for (Call call : mOkHttpClient.dispatcher().runningCalls()){if (tag.equals(call.request().tag())){call.cancel();}}}public static class METHOD{public static final String HEAD = "HEAD";public static final String DELETE = "DELETE";public static final String PUT = "PUT";public static final String PATCH = "PATCH";} }
要是沒有添加依賴的,去build.gradle添加依賴,沒有包的就ALT+ENTER引包。
再說一下這段請求代碼,搞過后臺的基本都能看懂。
OkHttpUtils.get().url(url).addParams("cuuid","66666").addParams("washDate", dateString).addParams("washTime",timeString).build().execute(new StringCallback() {@Overridepublic void onError(Call call, Exception e, int id) {Log.e("onError:", e.toString());}@Overridepublic void onResponse(String response, int id) {Log.e("onResponse:", response);JSONObject responseJson = (JSONObject) JSONObject.parse(response);String code = responseJson.getString("code");String message = responseJson.getString("message");//保存成功if("100".equals(responseJson.get("code"))){Toast.makeText(getApplicationContext(), code+","+responseJson.get("message"), Toast.LENGTH_LONG).show();}else{Toast.makeText(getApplicationContext(), code+","+responseJson.get("message"), Toast.LENGTH_LONG).show();}}});
發(fā)了一個get請求,參數(shù)是cuuid,washDate,washTime,這兩個時間就是上面從插件
選的。onResponse方法,需要返回標準的json格式,我這里定義的是
{"code":"100","message":"success"},后臺需要的接口,這里不寫了。
4.最后一步,打包
我這里沒有連手機,如果你連手機,打開開發(fā)者模式,顯示有你的手機,點擊ok就好了。
打成apk文件。
第一次打的話,讓你寫密碼什么的,一定要記住。。。
打好了就可以把apk分享給好友下載了。
貼一張我的app的圖。
總結(jié)
以上是生活随笔為你收集整理的利用Android Studio快速搭建App的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: nyoj--120--校园网络(scc+
- 下一篇: matlab 二进制写入文件,在Matl