[英]How Can I put all my If statement in only one class or function?
我的代碼中有很多 if 語句,是否可以創建一個函數或列表並將它們全部包含在其中?
我想總結一下這些 if 以減少我的代碼長度,以便我以后可以輕松更改它。 每次改變它都很難進入。 擁有一個包含所有這些 if 的大函數會更容易,然后我可以在添加新事件時操作它們。 有人可以幫我嗎?
public class MainActivity extends AppCompatActivity {
public static final String ERROR_DETECTED = "No NFC tag detected!";
public static final String WRITE_SUCCESS = "Text written to the NFC tag successfully!";
public static final String WRITE_ERROR = "Error during writing, is the NFC tag close enough to your device?";
NfcAdapter nfcAdapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
boolean writeMode;
Tag myTag;
Context context;
Button btnWrite;
View D1,D2,D3,D4,Autoprotection,Etat_centrale,Capot,Alimentation,PP4;
TextView tvNFCContent,message, nfc_annoce, CompteurTelecommandes,Conseil_detecteur,text_centrale,Telecommande_centrale,Titre_systeme,Titre_telecommande,Nbre_defauts4,Defauts_capot,Defauts_pion;
ImageView back,Batterie;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main );
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
context = this;
tvNFCContent = findViewById(R.id.contenu);
message = findViewById(R.id.ecriture);
PP4 =findViewById(R.id.pp4);
btnWrite = findViewById(R.id.ecrire_nfc);
Etat_centrale = findViewById(R.id.etat_final);
D1 = findViewById(R.id.detecteur_1);
D2 = findViewById(R.id.detecteur_2);
D3 = findViewById(R.id.detecteur_3);
D4 = findViewById(R.id.detecteur_4);
Alimentation = findViewById(R.id.alimentation);
Autoprotection = findViewById(R.id.tamper);
Capot = findViewById(R.id.capot);
Batterie = findViewById(R.id.batterie);
Telecommande_centrale= findViewById(R.id.telecommande_inconnu);
Defauts_capot=findViewById(R.id.defaut_capot);
Defauts_pion=findViewById(R.id.defaut_tamper);
CompteurTelecommandes=findViewById(R.id.compteur_télecommande);
Conseil_detecteur=findViewById(R.id.conseil);
text_centrale=findViewById(R.id.centrale_text);
Titre_systeme=findViewById(R.id.titre_systeme);
Titre_telecommande=findViewById(R.id.titre_telecommande);
// Mode_alimentation = findViewById(R.id.mode_alim);
//Telecommande_arret = findViewById(R.id.telecommande_arret);
//Telecommande_trame= findViewById(R.id.telecommande_trame);
//Telecommande_centrale= findViewById(R.id.telecommande_centrale);
//Nbre_defauts1= findViewById(R.id.nbre_defauts1);
//Nbre_defauts2= findViewById(R.id.nbre_defauts2);
//Nbre_defauts3= findViewById(R.id.nbre_defauts3);
//Nbre_defauts4= findViewById(R.id.nbre_defauts4);
PP4.setVisibility(View.GONE);
nfc_annoce = findViewById(R.id.textView4);
nfc_annoce.setVisibility(View.VISIBLE);
back=findViewById(R.id.Reader);
back.setVisibility(View.VISIBLE);
CompteurTelecommandes.setVisibility(View.GONE);
Conseil_detecteur.setVisibility(View.GONE);
text_centrale.setVisibility(View.GONE);
Titre_telecommande.setVisibility(View.GONE);
Titre_systeme.setVisibility(View.GONE);
D1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View a) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Détecteur 1"
);
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
D2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View b) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Détecteur 2");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
D3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View c) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Détecteur 3"
);
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
D4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View d) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Détecteur 4");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
btnWrite.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
try {
if(myTag ==null) {
Toast.makeText(context, ERROR_DETECTED, Toast.LENGTH_LONG).show();
} else {
write(message.getText().toString(), myTag);
Toast.makeText(context, WRITE_SUCCESS, Toast.LENGTH_LONG ).show();
}
} catch (IOException e) {
Toast.makeText(context, WRITE_ERROR, Toast.LENGTH_LONG ).show();
e.printStackTrace();
} catch (FormatException e) {
Toast.makeText(context, WRITE_ERROR, Toast.LENGTH_LONG ).show();
e.printStackTrace();
}
}
});
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "Cet appareil ne possède pas la technologie NFC", Toast.LENGTH_LONG).show();
finish();
}
readFromIntent(getIntent());
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
writeTagFilters = new IntentFilter[] { tagDetected };
}
/******************************************************************************
**********************************Read From NFC Tag***************************
******************************************************************************/
private void readFromIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs = null;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
}
buildTagViews(msgs);
}
}
private void buildTagViews(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0) return;
String text = "";
// String tagId = new String(msgs[0].getRecords()[0].getType());
byte[] payload = msgs[0].getRecords()[0].getPayload();
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
// String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
try {
// Get the Text
text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
tvNFCContent.setText(text+"(( taille de la trame: " + text.length () +"))");
//lenght.setText(text.length ());
//tramemail.setText(text+"(( taille de la trame: " + text.length () +"))" + Version);
nfc_annoce.setVisibility(View.GONE);
back.setVisibility(View.GONE);
//Nbre_defauts1.setText(" Le Nombre de défauts enregistrés sur le détecteur 1 est de "+ text.charAt(39)+ text.charAt(40));
//Nbre_defauts2.setText(" Le Nombre de défauts enregistrés sur le détecteur 2 est de "+ text.charAt(41)+ text.charAt(42));
//Nbre_defauts3.setText(" Le Nombre de défauts enregistrés sur le détecteur 3 est de "+ text.charAt(43)+ text.charAt(44));
//Nbre_defauts4.setText(" Le Nombre de défauts enregistrés sur le détecteur 4 est de "+ text.charAt(45)+ text.charAt(46));
//Nbre_defauts_pion.setText(" Le Nombre de défauts enregistrés sur l'autoprotection est de "+ text.charAt(57)+ text.charAt(58));
//Nbre_defauts_capot.setText(" Le Nombre de défauts enregistrés sur le capot est de "+ text.charAt(55)+ text.charAt(56));
CompteurTelecommandes.setVisibility(View.VISIBLE);
Conseil_detecteur.setVisibility(View.VISIBLE);
PP4.setVisibility(View.VISIBLE);
text_centrale.setVisibility(View.VISIBLE);
Titre_systeme.setVisibility(View.VISIBLE);
Titre_telecommande.setVisibility(View.VISIBLE);
if (text.charAt(6) == 'O')
{
Etat_centrale.setBackgroundResource(R.drawable.ic_ok);
} else
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Centrale en Alarme");
alertDialog.setMessage(" La centrale de sécurisation est en défaut.\n" +
"Une intervention de votre part est nécessaire !");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Fermer",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
Etat_centrale.setBackgroundResource(R.drawable.ic_warning_red);
}
if (text.charAt(7) == 'A') {
D1.setBackgroundResource(R.drawable.ic_warning_red);
} else if (text.charAt(7) == 'O') {
D1.setBackgroundResource(R.drawable.ic_ok);
} else if (text.charAt(7) == 'W') {
D1.setBackgroundResource(R.drawable.ic__warning_orange);
} else {
D1.setBackgroundResource(R.drawable.ic_baseline_block_24);
}
if (text.charAt(8) == 'A') {
D2.setBackgroundResource(R.drawable.ic_warning_red);
} else if (text.charAt(8) == 'O') {
D2.setBackgroundResource(R.drawable.ic_ok);
} else if (text.charAt(8) == 'W') {
D2.setBackgroundResource(R.drawable.ic__warning_orange);
} else {
D2.setBackgroundResource(R.drawable.ic_baseline_block_24);
}
if (text.charAt(9) == 'A') {
D3.setBackgroundResource(R.drawable.ic_warning_red);
} else if (text.charAt(9) == 'O') {
D3.setBackgroundResource(R.drawable.ic_ok);
} else if (text.charAt(9) == 'W') {
D3.setBackgroundResource(R.drawable.ic__warning_orange);
} else {
D3.setBackgroundResource(R.drawable.ic_baseline_block_24);
}
if (text.charAt(10) == 'A') {
D4.setBackgroundResource(R.drawable.ic_warning_red);
} else if (text.charAt(10) == 'O') {
D4.setBackgroundResource(R.drawable.ic_ok);
} else if (text.charAt(10) == 'W') {
D4.setBackgroundResource(R.drawable.ic__warning_orange);
} else {
D4.setBackgroundResource(R.drawable.ic_baseline_block_24);
}
if (text.charAt(59)== 'O'){
Capot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Autoprotection capot enclenchée", Toast.LENGTH_SHORT).show();
}
});
Capot.setBackgroundResource(R.drawable.capot_vert);
Defauts_capot.setVisibility(View.GONE);
}
else {
Capot.setBackgroundResource(R.drawable.capot_rouge);
Capot.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Défaut autoprotection capot \n" +
"Vérifiez que le capot est bien fermé et vissé");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
Defauts_capot.setText("Défaut autoprotection capot \n"+
"Vérifiez que le capot est bien fermé et vissé");
}
if (text.charAt(60) == 'O') {
Autoprotection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View e) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Autoprotection base enclenchée");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
Autoprotection.setBackgroundResource(R.drawable.pion_vert);
Defauts_pion.setVisibility(View.GONE); }
else {
Autoprotection.setBackgroundResource(R.drawable.pion_rouge);
Autoprotection.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View e) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Défaut autoprotection base \n" +
"Vérifiez le contact et la fixation de la centrale du mobilier.\n" +
"Selon l'installation, revissez ou re-adhésivez la centrale");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
Defauts_pion.setVisibility(View.VISIBLE);
Defauts_pion.setText("Défaut autoprotection base\n " +
"Vérifiez le contact et la fixation de la centrale au mobilier \n" +
"Selon l'installation, revissez ou re-adhésivez la centrale");
}
if (text.charAt(61) == 'P') {
Alimentation.setBackgroundResource(R.drawable.ic_baseline_power_vert);
Alimentation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Alimentation secteur");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
}
else if (text.charAt(61)== 'B') {
Alimentation.setBackgroundResource(R.drawable.ic_baseline_power_bleu);
Alimentation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Alimentation double secteur");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
}
else {
Alimentation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Alimentation pile");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
Alimentation.setBackgroundResource(R.drawable.ic_baseline_power_rouge);
}
if (text.charAt(62) == 'H') {
Batterie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Capacité de la pile (CR 123 A) optimale");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
Batterie.setBackgroundResource(R.drawable.batterie_full); }
else if (text.charAt(62)== 'M'){
Batterie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Pile (CR 123 A) à 50% de sa capacité");
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
Batterie.setBackgroundResource(R.drawable.batterie_midlle);
}
else if (text.charAt(62)== 'L'){
Batterie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Capacité de la pile (CR 123 A) faible \n" +
"\n"+
"Vite, remplacez-la ! "
);
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
Batterie.setBackgroundResource(R.drawable.batterie_vide);
}
else {
Batterie.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText("Aucune pile insérée." +
"Pour une installation 100% sécurisée, nous vous conseillons d'insérer une pile CR 123 A"
);
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
});
Batterie.setBackgroundResource(R.drawable.batterie_absente);
}
//int version = (int)text.charAt(4);
if (text.charAt(67)=='I'|| text.charAt(72)=='I') {
Telecommande_centrale.setVisibility(View.VISIBLE);
Telecommande_centrale.setText("Attention:des télécommandes inconnues ont été présentées à la centrale" +
"Consultez la procédure d'affection des télécommandes");
}
else{
Telecommande_centrale.setVisibility(View.GONE);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.action_share:
Intent sharingIntent =new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody= "Bonjour";
String shareSubject= "Retour SAV";
sharingIntent.putExtra(Intent.EXTRA_TEXT,shareBody);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT,shareSubject);
startActivity(Intent.createChooser(sharingIntent, "partager avec"));
break;
}
return super.onOptionsItemSelected(item);
}
/******************************************************************************
**********************************Write to NFC Tag****************************
******************************************************************************/
private void write(String text, Tag tag) throws IOException, FormatException {
NdefRecord[] records = { createRecord(text) };
NdefMessage message = new NdefMessage(records);
// Get an instance of Ndef for the tag.
Ndef ndef = Ndef.get(tag);
// Enable I/O
ndef.connect();
// Write the message
ndef.writeNdefMessage(message);
// Close the connection
ndef.close();
}
private NdefRecord createRecord(String text) throws UnsupportedEncodingException {
String lang = "en";
byte[] textBytes = text.getBytes();
byte[] langBytes = lang.getBytes("US-ASCII");
int langLength = langBytes.length;
int textLength = textBytes.length;
byte[] payload = new byte[1 + langLength + textLength];
// set status byte (see NDEF spec for actual bits)
payload[0] = (byte) langLength;
// copy langbytes and textbytes into payload
System.arraycopy(langBytes, 0, payload, 1, langLength);
System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
NdefRecord recordNFC = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], payload);
return recordNFC;
}
@Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
readFromIntent(intent);
if(NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
}
}
@Override
public void onPause(){
super.onPause();
WriteModeOff();
}
@Override
public void onResume(){
super.onResume();
WriteModeOn();
}
/******************************************************************************
**********************************Enable Write********************************
******************************************************************************/
private void WriteModeOn(){
writeMode = true;
nfcAdapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
}
/******************************************************************************
**********************************Disable Write*******************************
******************************************************************************/
private void WriteModeOff(){
writeMode = false;
nfcAdapter.disableForegroundDispatch(this);
}
}
您可以擁有一個包含值的 Map,因此您可以直接訪問它們。 例如:
final Map<Char, Integer> foo = new HashMap();
foo.add('A', R.drawable.ic_warning_red);
foo.add('O', R.drawable.ic_ok);
//... so on
然后你可以直接應用它
D3.setBackgroundResource(
Optional.ofNullable(foo.get(text.charAt(9)))
.orElse(R.drawable.ic_baseline_block_24));
減少我的代碼的長度,這樣我就可以很容易地改變它,因為每次改變它都很難
正如@Steve 所提議的,您可以重構代碼以使其更小且更易於修改/編輯。 一種可能的方法是說,創建一個方法 updateTextview()。 就像是
private void updateTextview(final String text){
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER,0,-150);
TextView tv = new TextView (MainActivity.this) ;
tv.setBackgroundResource(R.color.blanc);
tv.setTextColor(Color.BLACK);
tv.setTextSize(15);
tv.setText(text);
Typeface t = Typeface.create( "serif", Typeface.NORMAL);
tv.setTypeface(t);
tv.setPadding(50, 50,50,50);
toast.setView(tv);
toast.show();
}
PS:我注意到只有tv.setText()
發生了變化。 您可以根據函數的變化向函數添加更多參數。
要使用該方法,在 D1 上添加偵聽器 say 時,您可以使用類似
D1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View a) {
final String text = "Détecteur 1";
updateTextview(text);
}
});
此外,使用switch 語句(而不是 ifs)可以使您的代碼看起來更簡潔。 作為一個例子,我將從代碼中取出一小段 if-else-ifs。 text.charAt(7) 上的 ifs 改變了 D1 的 BackgroundResource。
char charAt7 = text.charAt(7);
switch(charAt7){
case 'A' : D1.setBackgroundResource(R.drawable.ic_warning_red); break;
case 'O' : D1.setBackgroundResource(R.drawable.ic_ok); break;
case 'W' : D1.setBackgroundResource(R.drawable.ic__warning_orange); break;
default: D1.setBackgroundResource(R.drawable.ic_baseline_block_24);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.