1

I was wondered if you have a lot of buttons in one activity if this is the right way to define them

FL = (Button) findViewById(R.id.FL);
RR = (Button) findViewById(R.id.RR);
RL = (Button) findViewById(R.id.RL);
FR = (Button) findViewById(R.id.FR);
clear = (Button) findViewById(R.id.clear);
save = (Button) findViewById(R.id.save);

VeLi = (TextView) findViewById(R.id.VeLi);

FRL = (EditText) findViewById(R.id.FRL);
RER = (EditText) findViewById(R.id.RER);
REL = (EditText) findViewById(R.id.REL);
FRR = (EditText) findViewById(R.id.FRR);

FL.setOnClickListener(onClickListener);
RR.setOnClickListener(onClickListener);
RL.setOnClickListener(onClickListener);
FR.setOnClickListener(onClickListener);
clear.setOnClickListener(onClickListener);
save.setOnClickListener(onClickListener);

now am i defining them all one by one is this the right way of is there for this an easier way..?

tnx

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Rikkert09
  • 190
  • 1
  • 1
  • 11

3 Answers3

3

It is the only way, unless you will use something like Android Annotations: https://github.com/excilys/androidannotations/wiki/Injecting-Views

You can also loop through elements if it will help. Here you will find some informations how to do it: How to iterate through a view's elements

Community
  • 1
  • 1
Klapsa2503
  • 829
  • 10
  • 33
1

Butter Knife is another tool that allows to bind view objects to variables and declare callback using annotations. You may:

Bind multiple view objects to list

@InjectViews({ R.id.first_name, R.id.middle_name, R.id.last_name })
List<EditText> nameViews;

Declarle callback function for multiple views

@OnClick({ R.id.door1, R.id.door2, R.id.door3 })
public void pickDoor(DoorView door) {

}

You still need to pass list of ids to annotations, but code is more concise than in standard approach. Check ButterKnife documentation for more use cases- this library is all about reducing boilerplate code.

It uses code generation (instead of slow reflection). For me, it is must-have for every Android project that has UI.

Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113
0

if you have lot of buttons then its better to implement OnClickListener interface in your class(activity of fragment ) see simple example implement.

public class Main extends Activity implements OnClickListener {

Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1=(Button)findViewById(R.id.button1);
    b2=(Button)findViewById(R.id.button2);
    b1.setOnClickListener(this);
    b2.setOnClickListener(this);

}

public void onClick(View v)
{
    switch(v.getId())
    {
    case R.id.button1:
    //Do something
        break;
    case R.id.button2:
    //Do something  
    break;
    }

}

this is the standard way of android to implements views.

khurram
  • 1,362
  • 13
  • 24