由于if语句,重复相同的代码

时间:2017-04-18 22:10:13

标签: java android xml

我目前正在开发我的大学GPA跟踪器应用程序(我是新手开发人员)。该应用程序的主页在纵向模式下运行良好,但我有几个关于我的应用程序的问题。我感谢所有的帮助。

  1. 我知道onSavedInstance之前已在这里得到解答,但我不知道如何将它合并到我的代码中。我不只是在寻找答案。如果有人能向我解释,我真的很感激。旋转时我的所有观点都会丢失,我知道这是由onSavedInstanceState引起的。

  2. 当方向发生变化时,我发现3列的网格布局更合适。用于(最多)8个按钮的2个列和用于floatActionButton的右侧的最​​后一列,因此我为横向创建了一个单独的xml目录和文件。我认为布局工作正常,但由于我在第82行遇到的问题,它不会每次都填充和崩溃(我按照文档说明但是它说它无法运行我归因于我的方法的onClick方法FAB on xml)。

  3. 我的floatActionButton,当向下滚动应用程序时,向下移动应用程序。每次我滚动布局或单击它以添加更多视图时,FAB就会下降。

  4. 我创建了2个if语句来处理每个方向更改的动态视图添加但我最后重复代码并且Java看起来像一团糟。

  5. 我很抱歉向您提供了如此混乱的代码。

    我的横向xml文件

    <?xml version="1.0" encoding="utf-8"?>
    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:fillViewport="true"
        >
    
        <GridLayout
            android:id="@+id/semester_grid_layout"
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:background="#FFFFFF"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:columnCount="3"
            android:rowCount="4"
            xmlns:app="http://schemas.android.com/apk/res-auto"
            tools:context="myapp.onur.journeygpacalculator.MainActivity">
    
    
                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/addActionButton"
                    android:layout_column="2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_margin="16dp"
                    android:clickable="true"
                    android:onClick="onFloatActionButtonClick"
                    android:longClickable="true"
                    app:backgroundTint="@color/colorPrimary"
                    android:tint="@color/colorWhite"
                    app:borderWidth="0dp"
                    android:src="@drawable/ic_add_black_48dp" />
    
        </GridLayout>
        </ScrollView>
    

    我的常规xml布局

    <?xml version="1.0" encoding="utf-8"?>
    
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        tools:context="myapp.onur.journeygpacalculator.MainActivity">
    
        <ScrollView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            >
            <LinearLayout
                android:id="@+id/main_layout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:padding="6dp">
            </LinearLayout>
        </ScrollView>
    
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/addActionButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentEnd="true"
            android:layout_margin="16dp"
            android:clickable="true"
            android:longClickable="true"
            android:onClick="onFloatActionButtonClick"
            android:src="@drawable/ic_add_black_48dp"
            android:tint="@color/colorWhite"
            app:backgroundTint="@color/colorPrimary"
            android:elevation="6dp"
            app:borderWidth="0dp"/>
    </RelativeLayout>
    

    我的主要活动

    public class MainActivity extends AppCompatActivity {
    
        int counter = 0;
    
        FloatingActionButton addingSemester;
        Button semesterButton;
        LinearLayout semesterLayout;
        GridLayout semesterGridLayout;
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                AppBarLayout.LayoutParams.MATCH_PARENT,
                AppBarLayout.LayoutParams.WRAP_CONTENT);
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            addingSemester = (FloatingActionButton) findViewById(R.id.addActionButton);
            semesterLayout = (LinearLayout) findViewById(R.id.main_layout);
            semesterGridLayout = (GridLayout)findViewById(R.id.semester_grid_layout);
            semesterButton = new Button(MainActivity.this);
    
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.menu.main, menu);
            return super.onCreateOptionsMenu(menu);
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
    
            if (id == R.id.delete) {
                new AlertDialog.Builder(MainActivity.this)
                .setTitle("Delete entry")
                        .setMessage("Are you sure you want to delete everything?")
                        .setCancelable(true)
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                semesterLayout.removeAllViews();
                                counter = 0;
                            }
                        })
                        .setNegativeButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
                return true;
            }
    
            return super.onOptionsItemSelected(item);
    
        }
    
        public void onFloatActionButtonClick(View view) {
            float screenRotation = semesterLayout.getOrientation();
            semesterButton = new Button(MainActivity.this);
            if (counter < 8) {
                semesterButton.setId(counter + 1);
                semesterButton.setText("Semester " + (counter + 1));
                semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
                semesterButton.setTextColor(Color.WHITE);
                lp.setMargins(24, 24, 24, 24);
                semesterButton.setLayoutParams(lp);
    
                if(screenRotation == Surface.ROTATION_0 || screenRotation == Surface.ROTATION_180){
                    semesterGridLayout.addView(semesterButton);
                    counter++;
                    semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            final Button b = (Button) v;
                            b.setTag(b.getText().toString());
                            b.setBackgroundColor(Color.RED);
                            b.setText("Delete");
    
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("Delete entry")
                                    .setMessage("Are you sure you want to delete this entry?")
                                    .setCancelable(true)
                                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            semesterGridLayout.removeView(b);
                                            counter--;
                                            for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
                                                ((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
                                            }
                                        }
                                    })
                                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            b.cancelLongPress();
                                            b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                                            b.setText(b.getTag().toString());
                                            dialog.cancel();
    
                                        }
                                    })
                                    .show();
                            return true;
                        }
                    });
    
                }else if(screenRotation == Surface.ROTATION_90){
                    semesterLayout.addView(semesterButton);
                    counter++;
                    semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            final Button b = (Button) v;
                            b.setTag(b.getText().toString());
                            b.setBackgroundColor(Color.RED);
                            b.setText("Delete");
    
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("Delete entry")
                                    .setMessage("Are you sure you want to delete this entry?")
                                    .setCancelable(true)
                                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            semesterLayout.removeView(b);
                                            counter--;
                                            for (int i = 0; i < semesterLayout.getChildCount(); i++) {
                                                ((Button) semesterLayout.getChildAt(i)).setText("Semester " + (i + 1));
                                            }
                                        }
                                    })
                                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog, int which) {
                                            b.cancelLongPress();
                                            b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                                            b.setText(b.getTag().toString());
                                            dialog.cancel();
    
                                        }
                                    })
                                    .show();
                            return true;
                        }
                    });
                }
    
            } else if (counter == 8) {
                Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
            }
        }
    }
    

1 个答案:

答案 0 :(得分:0)

在回应第4项时,如果您将相同的代码块(或与参数类似的代码)重构为私有方法,您会发现代码更易于阅读和理解。此外,如果对if语句的两个路径执行代码,则可以将该代码移到外面:

public void onFloatActionButtonClick(View view) {
    float screenRotation = semesterLayout.getOrientation();
    semesterButton = new Button(MainActivity.this);
    if (counter < 8) {
        semesterButton.setId(counter + 1);
        semesterButton.setText("Semester " + (counter + 1));
        semesterButton.setBackgroundColor(getColor(R.color.colorPrimary));
        semesterButton.setTextColor(Color.WHITE);
        lp.setMargins(24, 24, 24, 24);
        semesterButton.setLayoutParams(lp);

        if (screenRotation == Surface.ROTATION_0 || screenRotation == Surface.ROTATION_180) {
            semesterGridLayout.addView(semesterButton);
        } else if (screenRotation == Surface.ROTATION_90) {
            semesterLayout.addView(semesterButton);
        }

        // these lines moved outside the if statement blocks
        counter++;
        setOnLongClickListenerForSemesterButton();

    } else if (counter == 8) {
        Toast.makeText(MainActivity.this, "You cannot add more than 8 semesters", Toast.LENGTH_SHORT).show();
    }
}

// this method refactored from the duplicated code
private void setOnLongClickListenerForSemesterButton() {
    semesterButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            final Button b = (Button) v;
            b.setTag(b.getText().toString());
            b.setBackgroundColor(Color.RED);
            b.setText("Delete");

            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("Delete entry")
                    .setMessage("Are you sure you want to delete this entry?")
                    .setCancelable(true)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            semesterGridLayout.removeView(b);
                            counter--;
                            for (int i = 0; i < semesterGridLayout.getChildCount(); i++) {
                                ((Button) semesterGridLayout.getChildAt(i)).setText("Semester " + (i + 1));
                            }
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            b.cancelLongPress();
                            b.setBackgroundColor(ContextCompat.getColor(MainActivity.this, R.color.colorPrimary));
                            b.setText(b.getTag().toString());
                            dialog.cancel();

                        }
                    })
                    .show();
            return true;
        }
    });
}