How to simplify clicks on buttons in Java for Android?

Asked

Viewed 78 times

0

I’m starting to have a lot of buttons in the same Activity and as much as they are simple commands, the code is getting big, and it will get even bigger.

I wonder if there is a way to simplify by decreasing the amounts of lines:

For example to open an Activity have people who do so:

Intendt welcome = new Intent(Dashboard.this,WelcomeScreen.class);
startActivity(welcome); 

When you can do it in a single line like this:

startActivity(new Intent(Dashboard.this,WelcomeScreen.class));

Now with buttons, I’m doing like this:

--- no onCreate
    Button btn_welcome = findViewById(R.id.btn_welcome);
    btn_welcome.setOnClickListener(this);

--- no onClick
switch (view.getId()) {
    case R.id.btn_welcome:
        startActivity(new Intent(Dashboard.this,WelcomeScreen.class));
    break;
}

There is a way to simplify all this in a few lines?

Follow my entire class with every button:

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class Dashboard extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        Button btn_welcome = findViewById(R.id.btn_welcome);
        btn_welcome.setOnClickListener(this);

        Button btn_perfil = findViewById(R.id.btn_perfil);
        btn_perfil.setOnClickListener(this);

        Button btn_popup = findViewById(R.id.btn_popup);
        btn_popup.setOnClickListener(this);

        Button btn_intromd01 = findViewById(R.id.btn_intromd01);
        btn_intromd01.setOnClickListener(this);

        Button btn_spinners = findViewById(R.id.btn_spinners);
        btn_spinners.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_welcome:
                startActivity(new Intent(Dashboard.this,WelcomeScreen.class));
                break;
            case R.id.btn_perfil:
                startActivity(new Intent(Dashboard.this,perfil.class));
                break;
            case R.id.btn_popup:
                startActivity(new Intent(Dashboard.this,popup.class));
                break;
            case R.id.btn_intromd01:
                startActivity(new Intent(Dashboard.this,InstroSlidesMd01.class));
                break;
            case R.id.btn_spinners:
                startActivity(new Intent(Dashboard.this,SpinnerLayouts.class));
                break;
        }
    }
}

2 answers

1


Taking into account that its structure is similar to this:

Estrutura do projeto

You can use the attribute tag in its element Button and then use Reflection. With this you can capture the class, just passing as parameter, its name.

For this just set the attribute tag with the name of Activity to which button will redirect the user.

XML example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="br.com.valdeirpsr.stackoverflow.MainActivity"
    android:id="@+id/container"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button #1"
        android:tag=".ProfileActivity"/> <!-- Atributo TAG -->

    <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button #2"
        android:tag=".WelcomeActivity"/> <!-- Atributo TAG -->

    <Button
        android:id="@+id/btn3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button #2"
        android:tag=".AnotherActivity"/> <!-- Atributo TAG -->

</LinearLayout>

In Java, to capture the class by name, just use Class.forName. This function will return the object Class which may be used in Intent.

Example in Java:

package br.com.valdeirpsr.stackoverflow;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;

public class MainActivity extends Activity implements View.OnClickListener {

    private ViewGroup container;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
        findViewById(R.id.btn3).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn1:
            case R.id.btn2:
            case R.id.btn3:
                try {
                    startActivity(new Intent(MainActivity.this, Class.forName(
                            getPackageName().concat(v.getTag().toString())
                    )));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
  • 1

    Perfect, thanks. I didn’t know Class.forName, it will help me in many other things as well. I already tested your example and gave it right. You’ve improved a lot. Thank you.

0

For each Button you can assign the . setOnClickListener directly with your onClick method inside onCreate as in the example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dashboard);

    Button btn_welcome = findViewById(R.id.btn_welcome);
    btn_welcome.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(Dashboard.this,WelcomeScreen.class));
        }
    });

    Button btn_perfil = findViewById(R.id.btn_perfil);
    btn_perfil.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(Dashboard.this,perfil.class));
        }
    });
} 

This decreases Button’s reference distance with your onClick method, leaving the code smaller and more objective.

  • This doesn’t make the code any smaller Diego, on the contrary this method makes it huge. Imagine that you have 100 buttons, as will your class. See Valdeir’s answer that I put as chosen. His method makes the code much more simplified. Maybe it’s useful for you too. bjss

  • If the purpose of Buttons is always to open other Activitys it is useful, but my example is more versatile can be referenced not only on onCreate but in any part of code mainly when working with Listview and Basedapter

  • Ahh yes Diego, in my case it is only to open other activities anyway, but I understood your idea yes. Thank you for your reply ^_^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.