如何计算文本中的字符

时间:2014-06-30 05:41:51

标签: android character textwatcher character-limit

在我的应用程序中,我想计算edittext中的章程数...,并且在字符数达到限制后,计数器应该再次以140开始,我想以“140”的格式显示它/ 1“,字符限制达到0后,再次显示140,但增加1乘1,显示为”140/2“。我可以做任何建议吗???

edMessage.addTextChangedListener(new TextWatcher() {

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

            }

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

            }

            public void afterTextChanged(Editable s) {

                // Display Remaining Character with respective color
                 count = MAX_COUNT - s.length();
               Word_counter.setText(Integer.toString(count) + "/" + Integer.toString(word)  );

               Word_counter.setTextColor(Color.BLACK);
                if(count < 10)
                {
                     Word_counter.setTextColor(Color.YELLOW);
                }


            }
        });

1 个答案:

答案 0 :(得分:0)

请尝试这种方式,希望这有助于您解决问题。

<强> activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center">

    <EditText
        android:id="@+id/editText"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"/>

</LinearLayout>

<强> MainActivity.java

public class MainActivity extends Activity {

    private EditText editText;
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.editText);
        textView = (TextView) findViewById(R.id.textView);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {

                if(s.length()/140 == 0){
                    textView.setText("140");
                }else{
                    textView.setText("140/"+String.valueOf((s.length()/140)+1));
                }
            }
        });

    }
}