简体   繁体   中英

Avoid repeating button code in my Android app

I was developing and I thought of a little problem I'm encountering on Android development with Java. I have this MainActivity class. The view are just some buttons, and every button calls a different activity. Right now I have this code

public class MainActivity extends AppCompatActivity {
    private Button button;

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

    button = findViewById(R.id.pedidos);

    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(getApplicationContext(), PedidosActivity.class);
            startActivity(intent);
        }
    });
}

So, considering that I need to add two more buttons so I can start two more different activities depending on which button do I press, I would need two repeat this code n times for every new Activity that I add in the project. I believe that there must be a better way to do this. I already thought I could do a factory pattern, using a class as Interface with a method that would be callActivity() Like this:

public interface ActivityFactory(){
public OnClickListener setOnClickListener();
}

This method would recieve through parameters the context of the activity which is instantiating the new view, an Enum type with the different views as parameters, and it would return a new eventListener for the button that would get you to the new view, like this:

@Override
button.setOnClickListener(getContextActivity(), EnumClass.NewActivity);

I haven't found any kind of post/blog/thread about this subject, maybe because I'm still newbie with Android development, but I find this very interesting and valuable to know for any Android developer, so any kind of approach is truly appreciated.

EDIT: I think that I left part of the explanation, so I will add it here. I wanted to skip the instantiation of the new two buttons, so I wanted to know the way of only instantiate one button and give it the value of the view depending on which button you press.

You can create a single View.OnClickListener and use it in several buttons:

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    findViewById(R.id.button_1).setOnClickListener(mButtonsClickListener);
    findViewById(R.id.button_2).setOnClickListener(mButtonsClickListener);
    ....
}


private View.OnClickListener mButtonsClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_1:
                // Actions for button 1
                break;
            case R.id.button_2:
                // Actions for button 2
                break;

        }
    }
};

Make use of ButterKnife ,

It will bind all your views, ease of coding

eg:

class ExampleActivity extends Activity {
    @BindView(R.id.title) TextView title;
    @BindView(R.id.subtitle) TextView subtitle;
    @BindView(R.id.footer) TextView footer;

    @Override public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_activity);
        ButterKnife.bind(this);
        // TODO Use fields...
    }
}

and for handling click,

make use of this,

@OnClick({ R.id.door1, R.id.door2, R.id.door3 })
public void pickDoor(View view) {
    switch (view.getId()) {
    case R.id.door1:

        break;
    case R.id.door2:

        break;
    case R.id.door3:

        break;
    default:

        break;
    }
}

and add Android ButterKnife Zelezny plugin in android studio.

for more info, have a look ath this http://jakewharton.github.io/butterknife/

hope it may help you.

You can do it as - Let say you have activities A, B and C You want to call A, B and C from HomeActivity

First put a LinearLayout in HomeActivity layout as -

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_add_event"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    <!--Your container will hold your buttons-->
    <LinearLayout 
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        />
    </RelativeLayout>

Now in your HomeActivity create an Array of Class as -

public class HomeActivity extends AppCompatActivity implements View.OnClickListener{
    private Class[] arrayClass= {A.class, B.class,C.class}; // classes you want to open
      private String[] buttonNames= {"A", "B", "C"};  // button texts

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LinearLayout container = (LinearLayout)findViewId(R.id.container);
        // adding buttons in container
        for(int index=0;index<arrayClass.length && arrayClass.lenght == buttonNames.length; index++){
            Button button = new Button(this);
            button.setText(buttonNames[index]);
            button.setOnClickListener(this)
            button.setTag(arrayClass[index]);
            container.addView(button);
        }
    }

   @Override
    public void onClick(View v) {

    if(v.getTag() instanceOf Class ){
      // will open your particular activity
      startActivity(new Intent(this,(Class)v.getTag()));
    }

   }

}

Now just add new Class type and Name in your array. Your code works itself

implements the View.OnClickListener after that u can add findViewByid of button then take a button name and setOnClickListener(this); LIKE button.setOnClickListener(this);

See my below code :

public class EventsListActivity extends AppCompatActivity implements View.OnClickListener{

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_events_list);

        init();
    }
    private void init() {
        txtClose = (TextView) findViewById(R.id.txtClose);
        txtClose.setOnClickListener(this);

        txtAdd = (TextView) findViewById(R.id.txtAdd);
        txtAdd.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        case R.id.txtAdd:
            Intent intent = new Intent(this, AddEventActivity.class);
            startActivity(intent);
        break;

        case R.id.txtClose:
            finish();
        break;      
    }
}

Look this,

Class<?> c = Class.forName("SecondPage");
Intent newActivity = new Intent(this, c);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM