java - 使用 TextWatcher 计算 EditTexts 之间的平均值

标签 java android

我在 android studio 上的项目有问题,我需要你的帮助。我用 3 个 EditText 和一个 Textview 创建了一行。我想在 EditText 上写数字并在 Textview 上计算平均值。当我点击它时,我还使用一个按钮来创建一个新行。我在第一行实现了计算,但每次我尝试计算创建按钮的行时,我都没有得到结果。这是我的代码:

public class MainActivity extends AppCompatActivity {
private LinearLayout parentLinearLayout;
private BreakIterator resultsText;
EditText editText1;
EditText editText2;
EditText editText3;
TextView textViewResult;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    parentLinearLayout = (LinearLayout) findViewById(R.id.parent_linear_layout);
    editText1 = (EditText) findViewById(R.id.number_edit_text1);
    editText2 = (EditText) findViewById(R.id.number_edit_text2);
    editText3 = (EditText) findViewById(R.id.number_edit_text3);

    textViewResult = (TextView) findViewById(R.id.number_text_view);

    editText1.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());
        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    editText2.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    editText3.addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            textViewResult.setText(avg());

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
}

private String avg() {
    int number1;
    int number2;
    int number3;
    if(editText1.getText().toString() != "" && editText1.getText().length() > 0) {
        number1 = Integer.parseInt(editText1.getText().toString());
    } else {
        number1 = 0;
    }
    if(editText2.getText().toString() != "" && editText2.getText().length() > 0) {
        number2 = Integer.parseInt(editText2.getText().toString());
    } else {
        number2 = 0;
    }
    if(editText3.getText().toString() != "" && editText3.getText().length() > 0) {
        number3 = Integer.parseInt(editText3.getText().toString());
    } else {
        number3 = 0;
    }

    return Integer.toString((number1 + number2 + number3)/3 );
}

public void onAddField(View v) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.field, null);
    // Add the new row before the add field button.
    parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);


}

public void onDelete(View v) {
    parentLinearLayout.removeView((View) v.getParent());
}

}

还有两个 .xml 文件: activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent_linear_layout"
    android:layout_width="match_parent"
    android:layout_height="495dp"
    android:layout_margin="0dp"
    android:orientation="vertical"
    android:weightSum="1">

    <TableLayout
        android:id="@+id/tlTable01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#CCC"
        android:orientation="vertical"
        android:paddingTop="0dp"
        android:theme="@style/AppTheme">

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#7CFC00"
            android:gravity="center_horizontal"
            android:paddingBottom="1dp">

            <TextView
                android:id="@+id/textView"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#7CFC00"
                android:gravity="left"
                android:padding="5dp"
                android:text="Scoring List"
                android:textSize="18dp"
                android:textStyle="bold"
                android:typeface="serif" />

            <EditText
                android:layout_width="190dp"
                android:layout_height="match_parent"
                android:layout_marginLeft="1dp"
                android:background="#FFF"
                android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZαβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"
                android:gravity="center_horizontal"
                android:inputType="text"
                android:padding="5dp"
                android:text="Examiner's Name"
                android:textSize="18dp"
                android:textStyle="bold"
                android:typeface="serif" />
        </TableRow>
    </TableLayout>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:layout_weight="0.01"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="Student's Name"
        android:textStyle="bold"
        android:typeface="serif" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="User Interface"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="Functions"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="User Manual"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginLeft="5dp"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:text="AVG"
        android:textStyle="bold"
        android:typeface="serif"/>

    <TextView
        android:layout_height="match_parent"
        android:layout_weight="2.35"
        android:gravity="left"
        android:layout_marginLeft="5dp"
        android:layout_width="wrap_content" />
    </LinearLayout>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_weight="0.01"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/word_edit_text"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZαβγδεζηθικλμνξοπρστυφχψωΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ"
        android:gravity="center_horizontal"
        android:inputType="text" />

    <EditText
        android:id="@+id/number_edit_text1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <EditText
        android:id="@+id/number_edit_text2"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <EditText
        android:id="@+id/number_edit_text3"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:inputType="number" />

    <TextView
        android:id="@+id/number_text_view"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:gravity="center_horizontal"
        android:textSize="18dp"
        android:textStyle="bold"
        android:typeface="serif"
        android:layout_marginTop="9dp"/>

    <Button
        android:id="@+id/delete_button"
        android:layout_width="0dp"
        android:layout_height="40dp"
        android:layout_weight="2.15"
        android:background="@android:drawable/ic_delete"
        android:onClick="onDelete" />
</LinearLayout>

<Button
        android:id="@+id/add_field_button"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:background="#555"
        android:onClick="onAddField"
        android:paddingLeft="5dp"
        android:text="Add Field"
        android:textColor="#FFF" />
</LinearLayout>

和field.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal"
android:layout_weight="0.01">

<EditText
    android:id="@+id/number_edit_text"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text1"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text2"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<EditText
    android:id="@+id/number_edit_text3"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:inputType="textCapWords"
    android:gravity="center_horizontal" />
<TextView
    android:id="@+id/number_text_view"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="5"
    android:gravity="center_horizontal"
    android:textSize="18dp"
    android:textStyle="bold"
    android:typeface="serif"
    android:layout_marginTop="9dp"/>


<Button
    android:id="@+id/delete_button"
    android:layout_width="0dp"
    android:layout_height="40dp"
    android:layout_weight="2.15"
    android:background="@android:drawable/ic_delete"
    android:onClick="onDelete" />

</LinearLayout>

提前致谢!

最佳答案

这是适合您的工作代码:

public void onAddField(View v) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.field, null);
    ((EditText) rowView.findViewById(R.id.number_edit_text1)).addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub
        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            ((TextView) rowView.findViewById(R.id.number_text_view)).setText(
                    avg(((EditText) rowView.findViewById(R.id.number_edit_text1)),
                            ((EditText) rowView.findViewById(R.id.number_edit_text2)),
                            ((EditText) rowView.findViewById(R.id.number_edit_text3))));            }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
        }
    });

    ((EditText) rowView.findViewById(R.id.number_edit_text2)).addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            ((TextView) rowView.findViewById(R.id.number_text_view)).setText(
                    avg(((EditText) rowView.findViewById(R.id.number_edit_text1)),
                            ((EditText) rowView.findViewById(R.id.number_edit_text2)),
                            ((EditText) rowView.findViewById(R.id.number_edit_text3))));
        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    ((EditText) rowView.findViewById(R.id.number_edit_text3)).addTextChangedListener(new TextWatcher() {

        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
            ((TextView) rowView.findViewById(R.id.number_text_view)).setText(
                    avg(((EditText) rowView.findViewById(R.id.number_edit_text1)),
                            ((EditText) rowView.findViewById(R.id.number_edit_text2)),
                            ((EditText) rowView.findViewById(R.id.number_edit_text3))));

        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    // Add the new row before the add field button.
    parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount() - 1);


}

private String avg(EditText viewById, EditText viewById1, EditText viewById2) {
    int number1;
    int number2;
    int number3;
    if (viewById.getText().toString() != "" && viewById.getText().length() > 0) {
        number1 = Integer.parseInt(viewById.getText().toString());
    } else {
        number1 = 0;
    }
    if (viewById1.getText().toString() != "" && viewById1.getText().length() > 0) {
        number2 = Integer.parseInt(viewById1.getText().toString());
    } else {
        number2 = 0;
    }
    if (viewById2.getText().toString() != "" && viewById2.getText().length() > 0) {
        number3 = Integer.parseInt(viewById2.getText().toString());
    } else {
        number3 = 0;
    }

    return Integer.toString((number1 + number2 + number3) / 3);
}

它没有起作用,因为您没有为字段分配任何监听器。

此外,我建议您对要添加的 View 使用 RecyclerView

注意

avg 函数是新函数,不要替换成你的。

希望对你有帮助:)

关于java - 使用 TextWatcher 计算 EditTexts 之间的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47284361/

相关文章:

java - 解析 xml 时出错 : unbound prefix from com. google.android.gms.ads.AdView

android - 在 Activity 生命周期中返回时在本地重新加载数据而不是从服务器重新加载数据

ANDROID:帮助 LocationProvider

android - 使用 Retrofit(Okhttp) 时,如何从 android studio 中的 log cat 复制请求正文、 header (无标签)?

java - 比较Java中的两个字符串

java - Maven Java Fx 示例无法运行 - 不重复

java - 在Spring MVC中,如何映射/settings/、/settings/users/、/settings/users/delete等嵌套URL?

java - JasperReport : net. sf.jasperreports.engine.fill.JRExpressionEvalException:计算表达式时出错:

java - 如何将 SWT Spy 用于 SWT 应用程序?

java - 未创建 AlerDialog - java.lang.IllegalArgumentException : Activity#onCreateDialog did not create a dialog for id X