21xrx.com
2024-11-25 16:17:05 Monday
登录
文章检索 我的文章 写文章
开发Android应用的最佳实践
2023-06-12 04:56:18 深夜i     --     --
原生JAVA Android应用开发 MVP架构 Retrofit RecyclerView

在今天的移动互联网时代,Android应用的开发已经成为了一个热门话题。虽然现在有大量的开发工具可供选择,比如Kotlin和Flutter等,但是原生JAVA仍然是最值得一试的选择。本文将介绍一些原生JAVA开发Android应用的最佳实践,并提供相应的代码案例。

1. 使用MVP架构

MVP(Model-View-Presenter)是一种常见的Android应用架构。使用MVP可以将应用程序逻辑和界面分离,使得代码更加清晰、易于维护。下面是一个简单的MVP架构的代码示例:


public interface LoginContract {

  interface View {

    void showError(String message);

    void showSuccess();

  }

  interface Presenter {

    void login(String username, String password);

  }

  interface Model {

    void login(String username, String password, OnLoginListener listener);

  }

  interface OnLoginListener {

    void onSuccess();

    void onFailure(String message);

  }

}

public class LoginPresenter implements LoginContract.Presenter, LoginContract.OnLoginListener {

  private LoginContract.View mView;

  private LoginContract.Model mModel;

  public LoginPresenter(LoginContract.View view) {

    mView = view;

    mModel = new LoginModel();

  }

  @Override

  public void login(String username, String password) {

    mModel.login(username, password, this);

  }

  @Override

  public void onSuccess() {

    mView.showSuccess();

  }

  @Override

  public void onFailure(String message) {

    mView.showError(message);

  }

}

public class LoginActivity implements LoginContract.View {

  private LoginPresenter mPresenter;

  private EditText mUsername;

  private EditText mPassword;

  private Button mLoginButton;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_login);

    mPresenter = new LoginPresenter(this);

    mUsername = findViewById(R.id.username);

    mPassword = findViewById(R.id.password);

    mLoginButton = findViewById(R.id.login_button);

    mLoginButton.setOnClickListener(new View.OnClickListener() {

      @Override

      public void onClick(View v) {

        mPresenter.login(mUsername.getText().toString(), mPassword.getText().toString());

      }

    });

  }

  @Override

  public void showError(String message) {

    Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

  }

  @Override

  public void showSuccess() {

    Toast.makeText(this, "Login success!", Toast.LENGTH_SHORT).show();

    //跳转到下一页

  }

}

2. 使用Retrofit进行网络请求

在开发Android应用的过程中,网络请求是非常常见和重要的一部分。使用Retrofit可以大大简化网络请求的过程,并且提供了许多有用的功能,如异步请求、自定义请求头等。下面是一个使用Retrofit进行GET请求的代码示例:


public interface ApiService {

  @GET("https://api.github.com/users/{user}/repos")

  Call > getUserRepos(@Path("user") String user);

}

public class ApiManager {

  private static final String BASE_URL = "https://api.github.com/";

  private static final int TIMEOUT = 60;

  private ApiService mApiService;

  private ApiManager() {

    OkHttpClient client = new OkHttpClient.Builder()

        .connectTimeout(TIMEOUT, TimeUnit.SECONDS)

        .readTimeout(TIMEOUT, TimeUnit.SECONDS)

        .writeTimeout(TIMEOUT, TimeUnit.SECONDS)

        .build();

    Retrofit retrofit = new Retrofit.Builder()

        .baseUrl(BASE_URL)

        .client(client)

        .addConverterFactory(GsonConverterFactory.create())

        .build();

    mApiService = retrofit.create(ApiService.class);

  }

  public static ApiManager getInstance()

    return SingletonHolder.INSTANCE;

  

  private static class SingletonHolder {

    private static final ApiManager INSTANCE = new ApiManager();

  }

  public void getUserRepos(String user, Callback > callback) {

    Call > call = mApiService.getUserRepos(user);

    call.enqueue(callback);

  }

}

3. 使用RecyclerView展示列表数据

在实际开发中,展示列表数据是一项非常常见的任务。使用RecyclerView可以大大简化列表数据的展示,并且提供了各种以极其有用的功能,如多类型列表、动画效果等。下面是一个使用RecyclerView展示单一类型数据的代码示例:


public class RecyclerViewActivity extends AppCompatActivity {

  private RecyclerView mRecyclerView;

  private MyAdapter mAdapter;

  private List mData;

  @Override

  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_recycler_view);

    mData = new ArrayList<>();

    for (int i = 0; i < 50; i++) {

      mData.add("Item " + i);

    }

    mRecyclerView = findViewById(R.id.recycler_view);

    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mAdapter = new MyAdapter(mData);

    mRecyclerView.setAdapter(mAdapter);

  }

  private static class MyAdapter extends RecyclerView.Adapter {

    private List mData;

    public MyAdapter(List data)

      mData = data;

    

    @Override

    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

      View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);

      return new MyViewHolder(view);

    }

    @Override

    public void onBindViewHolder(MyViewHolder holder, int position) {

      holder.mTextView.setText(mData.get(position));

    }

    @Override

    public int getItemCount() {

      return mData.size();

    }

  }

  private static class MyViewHolder extends RecyclerView.ViewHolder {

    private TextView mTextView;

    public MyViewHolder(View itemView) {

      super(itemView);

      mTextView = itemView.findViewById(R.id.text_view);

    }

  }

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章