如何使 findViewByID 全局化

How make findViewByID global

晚上好,

我有问题,我想将 "finViewById" 声明一次为全局。但它只能作为本地的,所以我必须复制和粘贴它们,这很糟糕。

public class MainActivity 扩展 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;
                }
            }
    );
}

制作工具栏、mygtukas 和 laukelis 全局变量

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);
    ...

然后您可以使用 class 在任何地方访问它们。

我相信您想要实现的是在匿名 class 中捕获局部变量,如 here. However, you can only capture variables marked as 'final'. You can have a look here 所述,如果您需要进一步说明。