使用AndroidStudio开发安卓应用大致分为三步:
1、创建一个Android项目或者Android模块
2、在XML布局文件中定义应用程序的用户界面
3、在Java代码中编写业务实现
activty_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/toast_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text= "@string/toastBtn"/> 注意此处的text字符串引用方式,这里的字符串预先在string中定义
</LinearLayout>
strings.xml
<resources>
<string name="app_name">Toast</string>
<string name="toastBtn">弹窗</string>
</resources>
MainActivity.java
package com.ryshine.toast;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//创建Toast对象为null
static Toast toast = null;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.toast_btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ToastShow(MainActivity.this, "弹窗");
}
});
}
//这里弹窗的代码可以避免多次点击按钮,弹窗一直叠加时间弹出的问题
//点击一次按钮,弹窗弹出,弹窗未消失时再次点击按钮,弹窗则重新设置时间与弹窗文本,不会产生弹窗时间叠加
public void ToastShow(Context context, String s){
//如果toast为null,说明之前没有为Toast对象初始化,即这是第一次对Toast操作
if (toast == null){
toast = Toast.makeText(context, s, Toast.LENGTH_SHORT);
}else {
//如果Toast对象已经存在,且有过操作,则重新设置String与弹窗时间
toast.setText(s);
toast.setDuration(Toast.LENGTH_SHORT);
}
//show()
toast.show();
}
}
AndroidMainfest.xml
安卓四大组件使用前都需要在AndroidMainfest中注册
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ryshine.toast">
<application 注意这里的格式
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity"> 注意这里的格式
<intent-filter> 注意这里的格式
<action android:name="android.intent.action.MAIN"/> 注意这里的格式
<category android:name="android.intent.category.LAUNCHER"/> 注意这里的格式
</intent-filter>
</activity>
</application> 注意这里的格式
</manifest>
截图如下

本文介绍使用Android Studio开发安卓应用的基本步骤,包括创建项目、定义用户界面及编写业务逻辑。通过实例演示了如何创建按钮并实现弹窗功能。
806

被折叠的 条评论
为什么被折叠?



