我是否必须(在每个函数中)再次声明一个 UI 元素(例如(按钮)按钮)或者是否有更简单的方法来做到这一点。 (这不是最终的代码,它只是给出一个例子来说明我的意思(有一个解密函数和一个简单的清除按钮)。这是我用 Java 编写的第一个程序,因此非常欢迎任何提示/改进!
公共(public)类 MainActivity 扩展 Activity {
View.OnLongClickListener Longpress = new View.OnLongClickListener()
{
//A mess around with Toast - long pressing buttons will (eventually) give a description of their purpose
@Override
public boolean onLongClick(View v) {
Button heldButton = (Button)v;
String heldButtonText = heldButton.getText().toString();
Toast.makeText(getApplicationContext(), heldButtonText, Toast.LENGTH_LONG).show();
return true;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonCompute = (Button)findViewById(R.id.btn_compute);
Button buttonClear = (Button)findViewById(R.id.btn_clear);
Button buttonSwitch = (Button)findViewById(R.id.btn_switch);
buttonClear.setOnLongClickListener(Longpress);
buttonCompute.setOnLongClickListener(Longpress);
buttonSwitch.setOnLongClickListener(Longpress);
}
public void onButtonPress(View view)
{
TextView output_textView = (TextView)findViewById(R.id.Output);
TextView input_textView = (TextView)findViewById(R.id.Input);
int pos;
RadioButton encrypt = (RadioButton)findViewById(R.id.rdo_encrypt);
RadioButton decrypt = (RadioButton)findViewById(R.id.rdo_decrypt);
if(encrypt.isChecked()!= false || decrypt.isChecked()!= false )
{
if (encrypt.isChecked()==true)
{
output_textView.setText(encryptme(input_textView.getText().toString()));
}
if (decrypt.isChecked()==true)
{
output_textView.setText(decryptme(input_textView.getText().toString()));
}
}
else
{
new AlertDialog.Builder(this)
.setTitle("Error!")
.setMessage("Please check one radio button")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
}
private String encryptme(String inp)
{
TextView password_textView= (TextView)findViewById(R.id.Password);
int pos=0;
String password = password_textView.getText().toString();
char[] chararray = password.toCharArray();
String result = "";
for(char c : inp.toCharArray())
{
if(pos>=password.length())
{
pos=0;
char keychar = chararray[pos];
result += (char)(c + keychar);
pos+=1;
}
else
{
char keychar = chararray[pos];
result += (char)(c + keychar);
pos+=1;
}
}
return result;
}
最佳答案
在类级别定义所有数据类型和对象,然后您可以在类的任何方法中的任何位置使用它,而无需再次初始化它。
比如,
public class MainActivity extends Activity{
Button btn;
onCreate(Bundle icreate){
super.onCreate(icreate);
setContentView(R.layout.main_layout);
bnt = (Button) findViewById(R.id.buttonId);
}
public void anyMethod(){
//here you can use btn without defining it again
//suppose you are setting onClickListener then
btn.setOnClickListener(new View...){
....
}
}
}
关于java - 在 Java (android) 中高效地声明 UI 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28680524/