如何随机创建和分配变量并缩短if-else语句(Java android)



我想知道如何通过自动创建和分配TextView变量来缩短我的代码。另外,您如何缩短这些if-else语句?我查看了其他线程,但它们没有满足我的需求。我正在使用Android Studio。

这是我的Java代码:

package com.example.ani.testproject;
import android.graphics.Color;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;

public class MainScreen extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_screen);
    final TextView spot1 = (TextView) findViewById(R.id.spot1);
    final TextView spot2 = (TextView) findViewById(R.id.spot2);
    final TextView spot3 = (TextView) findViewById(R.id.spot3);
    final TextView spot4 = (TextView) findViewById(R.id.spot4);
    final TextView spot5 = (TextView) findViewById(R.id.spot5);
    final TextView spot6 = (TextView) findViewById(R.id.spot6);
    final TextView spot7 = (TextView) findViewById(R.id.spot7);
    final TextView spot8 = (TextView) findViewById(R.id.spot8);
    final TextView spot9 = (TextView) findViewById(R.id.spot9);
    final TextView spot10 = (TextView) findViewById(R.id.spot10);
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick (View v) {
            int loopnum = 1;
            while(loopnum<4){
                Random r = new Random();
                int spotnumber = r.nextInt(11-1) + 1;
                if(spotnumber==1){
                    spot1.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==2){
                    spot2.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==3){
                    spot3.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==4){
                    spot4.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==5){
                    spot5.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==6){
                    spot6.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==7){
                    spot7.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==8){
                    spot8.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==9){
                    spot9.setBackgroundColor(Color.RED);
                }
                else if(spotnumber==10){
                    spot10.setBackgroundColor(Color.RED);
                }
                loopnum += 1;
                SystemClock.sleep(5000);
            }
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main_screen, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

我真的无法清楚地显示这一点,但最后一个括号对应于以下括号:

public class MainScreen extends ActionBarActivity {

这是我的XML代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation = "horizontal">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="170dp"
    android:layout_height="match_parent"
    android:orientation = "vertical"
    android:layout_marginTop = "5dp"
    android:layout_marginRight = "5dp"
    android:id="@+id/linearLayout">
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot1"
        android:layout_marginTop="10dp"
        android:background="#ffffff"/>
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot2"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:background="#ffffff"/>
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot3"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:background="#ffffff"/>
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot4"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:background="#ffffff"/>
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot5"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:background="#ffffff"/>

</LinearLayout>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="170dp"
    android:layout_height="match_parent"
    android:orientation = "vertical"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_marginTop = "5dp"
    android:id="@+id/LinearLayout2">
    <Button
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Press Me"
        android:id="@+id/button"
        android:layout_gravity="right" />
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot6"
        android:layout_marginTop="10dp"
        android:layout_alignParentRight = "true"
        android:background="#ffffff"/>
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot7"
        android:layout_marginTop="10dp"
        android:layout_alignParentRight = "true"
        android:background="#ffffff"/>
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot8"
        android:layout_marginTop="10dp"
        android:layout_alignParentRight = "true"
        android:background="#ffffff"/>
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot9"
        android:layout_marginTop="10dp"
        android:layout_alignParentRight = "true"
        android:background="#ffffff"/>
    <TextView
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:id = "@+id/spot10"
        android:layout_marginTop="10dp"
        android:layout_alignParentRight = "true"
        android:background="#ffffff"/>

</LinearLayout>

请帮帮我!我是Android和Java的新手。

看起来保留

一个TextView列表,而不是每个变量的单个变量,适合您的情况。我们可以使用 ArrayList ,并通过从布局 xml 中指定的名称中检索TextView的 ID 来填充它。

ArrayList<TextView> spots = new ArrayList<TextView>();
for(int i = 1; i < 11; i++) {
    int id = getResources().getIdentifier("spot" + i, "id", getPackageName());
    spots.add((TextView) findViewById(id));
}

这将大大简化代码的另一部分,因为我们现在根本不需要任何if

Random r = new Random();
int spotnumber = r.nextInt(10);
spots.get(spotnumber).setBackgroundColor(Color.RED);

如果你想缩短你的 if =>else if 语句,你可以使用 switch 语句。

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html

基本上,您给开关一个变量,然后根据给定变量的值提供一组案例场景。在您的情况下,它看起来像这样:

switch (spotnumber) {
case 1 : //case scenario with spotnumber = 1
   spot1.setBackgroundColor(Color.RED);
   break;
case 2 :  //case scenario with spotnumber = 2
   spot2.setBackgroundColor(Color.RED);
   break;
}

不要忘记"break",否则匹配场景之后的每个语句都会被执行。

一个可能的解决方案是使用依赖注入。但是,Android 最佳实践并不推荐这种方法。你也许可以自动化你的函数,并使用数组列表存储文本视图。

List<TextView> spotList= new ArrayList<TextView>();
for(int i = 1; i <= 10; i++) {
    int id = getResources().getIdentifier("spot" + i, "id", getPackageName());
    spotList.add((TextView) findViewById(id));
}

if-else 语句将使用开关大小写进行修改:

switch (spotnumber) {
case 1 : //equivalent of spotnumber==1
   spot1.setBackgroundColor(Color.RED);
   break;
case 2 :  //equivalent of if spotnumber==2
   spot2.setBackgroundColor(Color.RED);
   break;
. 
.
.
}

最新更新