-2

Good evening,

I have a problem, I want to declare "finViewById" one time as global. But it only works as local one and so I have to copy and paste them, which is bad.

public class MainActivity extends AppCompatActivity {

//(I WANT HERE)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //(IT ONLY works HERE)
    Button mygtukas = (Button) findViewById(R.id.pgrButton);
    mygtukas.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TextView laukelis = (TextView) findViewById(R.id.pgrTekst);
                    laukelis.setText("Bamm, trumpas");
                }
            }
    );
    mygtukas.setOnLongClickListener(
            new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                //(I DON'T WANT THIS COPY as well)
              TextView laukelis =(TextView)findViewById(R.id.pgrTekst);
                    laukelis.setText("Bamm, ilgas");
                    return true;
                }
            }
    );
}

2 Answers2

6

Make toolbar, mygtukas and laukelis global variables

private Toolbar toolbar
private Button mygtukas
private TextView laukelis
@Override
protected void onCreate(Bundle savedInstanceState) {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    mygtukas = (Button) findViewById(R.id.pgrButton);
    laukelis = (TextView) findViewById(R.id.pgrTekst);
    ...

Then you can access them anywhere with the class.

Mike
  • 5,482
  • 2
  • 21
  • 25
1

I believe what you're trying to achieve is capturing local variable inside an anonymous class as described here. However, you can only capture variables marked as 'final'. You can have a look here if you need further clarification.

orhtej2
  • 2,133
  • 3
  • 16
  • 26