晚上好,
我遇到了问题,我想申报" finViewById"有一次是全球性的。但它只能作为本地用途,因此我必须复制并粘贴它们,这很糟糕。
公共类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;
}
}
);
}
答案 0 :(得分:4)
制作工具栏,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);
...
然后你可以在课堂的任何地方访问它们。
答案 1 :(得分:0)