Android编程,作为移动应用开发的主流技术之一,拥有庞大的用户群体和丰富的应用场景。学会Android编程,不仅能让你在就业市场上更具竞争力,还能让你在实现创意的过程中感受到编程的乐趣。本文将为你提供50个实用的Android编程实例,深度解析每一个实例,帮助你快速掌握Android编程的核心技能。
实例1:Android界面布局
解析: 界面布局是Android应用的基础,掌握布局方式对于开发出美观、易用的应用至关重要。以下是一个使用RelativeLayout布局的示例代码:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, Android!"
android:layout_centerInParent="true" />
</RelativeLayout>
实例2:Android事件处理
解析: 事件处理是Android应用与用户交互的关键。以下是一个按钮点击事件的示例代码:
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 点击事件处理代码
}
});
实例3:Android数据存储
解析: 数据存储是Android应用中必不可少的功能。以下是一个使用SharedPreferences存储数据的示例代码:
SharedPreferences sharedPreferences = getSharedPreferences("MyApp", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name", "张三");
editor.putInt("age", 25);
editor.apply();
实例4:Android网络请求
解析: 网络请求是Android应用获取数据的重要途径。以下是一个使用OkHttp库发送GET请求的示例代码:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.example.com/api/data")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 请求失败处理
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 请求成功处理
}
});
实例5:Android图片加载
解析: 图片加载是Android应用中常见的功能。以下是一个使用Glide库加载图片的示例代码:
Glide.with(context)
.load("https://www.example.com/image.jpg")
.into(imageView);
实例6:Android通知
解析: 通知是Android应用与用户沟通的重要方式。以下是一个创建简单通知的示例代码:
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this)
.setContentTitle("通知标题")
.setContentText("通知内容")
.setSmallIcon(R.drawable.ic_notification)
.build();
notificationManager.notify(1, notification);
实例7:Android权限请求
解析: 权限请求是Android 6.0及以上版本引入的新特性。以下是一个请求相机权限的示例代码:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, 1);
}
实例8:Android数据库操作
解析: 数据库操作是Android应用存储大量数据的关键。以下是一个使用SQLite数据库存储数据的示例代码:
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase("/data/data/com.example.app/database.db", null);
database.execSQL("CREATE TABLE IF NOT EXISTS user (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER)");
实例9:Android服务
解析: 服务是Android应用在后台执行任务的关键。以下是一个创建服务的示例代码:
public class MyService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 服务启动后执行的任务
return START_STICKY;
}
}
实例10:Android广播接收器
解析: 广播接收器是Android应用监听系统或应用事件的关键。以下是一个注册广播接收器的示例代码:
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.app.ACTION_BROADCAST");
registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 广播接收器处理代码
}
}, filter);
实例11:Android适配器
解析: 适配器是Android列表界面展示数据的关键。以下是一个自定义适配器的示例代码:
public class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_list, parent, false);
}
// 设置列表项数据
return convertView;
}
}
实例12:Android动画
解析: 动画是Android应用提升用户体验的重要手段。以下是一个简单的透明度动画示例代码:
<objectAnimator
xmlns:android="http://schemas.android.com/apk/res/android"
android:propertyName="alpha"
android:duration="1000"
android:valueFrom="1.0"
android:valueTo="0.0"
android:valueType="floatType" />
实例13:Android传感器
解析: 传感器是Android应用获取设备信息的关键。以下是一个获取加速度传感器数据的示例代码:
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
Sensor sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
// 传感器数据变化处理
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// 传感器精度变化处理
}
}, sensor, SensorManager.SENSOR_DELAY_NORMAL);
实例14:Android多线程
解析: 多线程是Android应用提高性能的关键。以下是一个使用HandlerThread的示例代码:
HandlerThread handlerThread = new HandlerThread("MyThread");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable() {
@Override
public void run() {
// 线程任务处理
}
});
实例15:Android自定义组件
解析: 自定义组件是Android应用提升用户体验的重要手段。以下是一个自定义View的示例代码:
public class MyView extends View {
public MyView(Context context) {
super(context);
// 初始化代码
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制代码
}
}
实例16:Android适配不同屏幕
解析: 适配不同屏幕是Android应用开发的基本要求。以下是一个使用dp单位确保组件在不同屏幕上显示一致的示例代码:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="宽度:"
android:layout_margin="16dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="高度:"
android:layout_margin="16dp" />
</LinearLayout>
实例17:Android使用Material Design
解析: Material Design是Android官方推荐的设计风格。以下是一个使用Material Design组件的示例代码:
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="CardView内容"
android:padding="16dp" />
</android.support.v7.widget.CardView>
实例18:Android使用RecyclerView
解析: RecyclerView是Android 2.0及以上版本引入的列表组件,相较于ListView具有更高的性能。以下是一个使用RecyclerView的示例代码:
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" />
实例19:Android使用ViewModel
解析: ViewModel是Android Architecture Components中的一部分,用于存储和管理界面相关的数据。以下是一个使用ViewModel的示例代码:
public class MyViewModel extends ViewModel {
// ViewModel数据和方法
}
实例20:Android使用LiveData
解析: LiveData是Android Architecture Components中的一部分,用于观察数据变化。以下是一个使用LiveData的示例代码:
public class MyLiveData extends LiveData<String> {
@Override
protected void onActive() {
super.onActive();
// LiveData数据变化处理
}
}
实例21:Android使用Room数据库
解析: Room是Android Architecture Components中的一部分,用于简化数据库操作。以下是一个使用Room数据库的示例代码:
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
实例22:Android使用Picasso库加载图片
解析: Picasso是Android社区常用的图片加载库。以下是一个使用Picasso加载图片的示例代码:
Picasso.with(context)
.load("https://www.example.com/image.jpg")
.into(imageView);
实例23:Android使用Gson库解析JSON
解析: Gson是Android社区常用的JSON解析库。以下是一个使用Gson解析JSON的示例代码:
Gson gson = new Gson();
User user = gson.fromJson(jsonString, User.class);
实例24:Android使用OkHttp库发送网络请求
解析: OkHttp是Android社区常用的网络请求库。以下是一个使用OkHttp发送GET请求的示例代码:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.example.com/api/data")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
// 请求失败处理
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// 请求成功处理
}
});
实例25:Android使用Retrofit库进行网络请求
解析: Retrofit是Android社区常用的网络请求库。以下是一个使用Retrofit发送GET请求的示例代码:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
MyApi myApi = retrofit.create(MyApi.class);
myApi.getData().enqueue(new Callback<MyData>() {
@Override
public void onFailure(Call<MyData> call, Throwable t) {
// 请求失败处理
}
@Override
public void onResponse(Call<MyData> call, Response<MyData> response) {
// 请求成功处理
}
});
实例26:Android使用Volley库进行网络请求
解析: Volley是Android社区常用的网络请求库。以下是一个使用Volley发送GET请求的示例代码:
RequestQueue requestQueue = Volley.newRequestQueue(context);
StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://www.example.com/api/data", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// 请求成功处理
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// 请求失败处理
}
});
requestQueue.add(stringRequest);
实例27:Android使用Glide库加载图片
解析: Glide是Android社区常用的图片加载库。以下是一个使用Glide加载图片的示例代码:
Glide.with(context)
.load("https://www.example.com/image.jpg")
.into(imageView);
实例28:Android使用Picasso库加载图片
解析: Picasso是Android社区常用的图片加载库。以下是一个使用Picasso加载图片的示例代码:
Picasso.with(context)
.load("https://www.example.com/image.jpg")
.into(imageView);
实例29:Android使用Universal Image Loader库加载图片
解析: Universal Image Loader是Android社区常用的图片加载库。以下是一个使用Universal Image Loader加载图片的示例代码:
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage("https://www.example.com/image.jpg", imageView);
实例30:Android使用ImageResizer库加载图片
解析: ImageResizer是Android社区常用的图片加载库。以下是一个使用ImageResizer加载图片的示例代码:
ImageResizer imageResizer = new ImageResizer();
imageResizer.resizeImage("https://www.example.com/image.jpg", imageView.getWidth(), imageView.getHeight(), new ImageResizer
