如何在键入之前和之后更改EditText中的文本

时间:2013-11-11 16:28:37

标签: java android

我有一个EditText,默认情况下它的字符串为“[]”。 我想要的是当用户选择EditText时,括号和空格全部消失。然后在完成编辑之后,我想将括号放在他们的编辑周围。

因此,例如,如果他们键入“123”,那么当他们完成输入时,EditText将显示“[123]”。

我尝试按照这里的答案EditText not updated after text changed in the TextWatcher,在afterTextChanged上对EditText执行setText,但是会抛出错误。

感谢您的帮助。

这是我的代码: 我刚刚添加了创建程序第一行的xml,因为那是我遇到问题的行。

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- Top Information -->

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".70"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <EditText
                    android:id="@+id/main_character_name_edit"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".25"
                    android:hint="@string/main_character_name_edit_hint" />

                <EditText
                    android:id="@+id/main_player_name_edit"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".25"
                    android:hint="@string/main_player_name_edit_hint" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".05"
                    android:gravity="right"
                    android:paddingRight="7dp"
                    android:text="@string/main_tl_view" />

                <EditText
                    android:id="@+id/main_tl_edit"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".10"
                    android:gravity="center_horizontal"
                    android:inputType="number" />

                <EditText
                    android:id="@+id/main_tl_cost_edit"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".05"
                    android:gravity="center_horizontal"
                    android:inputType="numberSigned"
                    android:text="@string/cost_edit" />
            </LinearLayout>

            <EditText
                android:id="@+id/main_character_description_edit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="top|left"
                android:hint="@string/main_character_description_edit"
                android:lines="2"
                android:maxLines="10"
                android:minLines="2"
                android:scrollbars="vertical" />
        </LinearLayout>

        <!-- Points Box -->

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".30"
            android:background="@drawable/border"
            android:orientation="vertical"
            android:padding="10dp" >

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:text="@string/main_points_view" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".25"
                    android:text="@string/main_points_total_view" />

                <EditText
                    android:id="@+id/main_points_total_edit"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".75"
                    android:gravity="center_horizontal"
                    android:inputType="number" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal" >

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".25"
                    android:text="@string/main_points_unspent_view" />

                <EditText
                    android:id="@+id/main_points_unspent_edit"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".75"
                    android:gravity="center_horizontal"
                    android:inputType="number" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

MainActivity.java

package com.gmail.james.grider.gurpscharactersheet;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;

public class MainActivity extends Activity {
    /* -- Top Info -- */
    private EditText mMainCharacterEdit, mMainPlayerEdit, mMainTlEdit,
            mMainTlCostEdit, mMainDescriptionEdit;

    /* -- Points Box -- */
    private EditText mMainPointsTotalEdit, mMainPointsUnspentEdit;

    /* -- Stats Derived Box -- */
    private EditText mMainFirstStatsDerivedHpTotalEdit,
            mMainFirstStatsDerivedHpCostEdit,
            mMainFirstStatsDerivedHpCurrentEdit,
            mMainFirstStatsDerivedFpTotalEdit,
            mMainFirstStatsDerivedFpCostEdit,
            mMainFirstStatsDerivedFpCurrentEdit,
            mMainFirstStatsDerivedWillEdit, mMainFirstStatsDerivedWillCostEdit,
            mMainFirstStatsDerivedPerEdit, mMainFirstStatsDerivedPerCostEdit;

    /* -- Stats Boxes -- */
    private EditText mMainSecondStStEdit, mMainSecondStCostEdit,
            mMainSecondStLastSkillEdit, mMainSecondStLastLvlEdit,
            mMainSecondStLastRelEdit, mMainSecondStLastCostEdit;
    private TableLayout mStatStSkillTable;
    private EditText mMainSecondDxDxEdit, mMainSecondDxCostEdit,
            mMainSecondDxLastSkillEdit, mMainSecondDxLastLvlEdit,
            mMainSecondDxLastRelEdit, mMainSecondDxLastCostEdit;
    private TableLayout mStatDxSkillTable;
    private EditText mMainSecondIqIqEdit, mMainSecondIqCostEdit,
            mMainSecondIqLastSkillEdit, mMainSecondIqLastLvlEdit,
            mMainSecondIqLastRelEdit, mMainSecondIqLastCostEdit;
    private TableLayout mStatIqSkillTable;
    private EditText mMainSecondHtHtEdit, mMainSecondHtCostEdit,
            mMainSecondHtLastSkillEdit, mMainSecondHtLastLvlEdit,
            mMainSecondHtLastRelEdit, mMainSecondHtLastCostEdit;
    private TableLayout mStatHtSkillTable;

    /* -- Secondary Stats Box -- */
    private EditText mMainThirdSecondaryLiftEdit, mMainThirdSecondarySpeedEdit,
            mMainThirdSecondarySpeedCostEdit, mMainThirdSecondaryBasicMoveEdit,
            mMainThirdSecondaryBasicMoveCostEdit, mMainThirdSecondaryMoveEdit;
    private Spinner mMainThirdSecondaryDamageThrustSpinner,
            mMainThirdSecondaryDamageSwingSpinner,
            mMainThirdSecondaryEncumbranceSpinner;

    /* -- Defense Box -- */
    private EditText mMainFourthDefenseDamageReductionEdit,
            mMainFourthDefenseDodgeEdit, mMainFourthDefenseParryEdit,
            mMainFourthDefenseBlockEdit;

    private void updateSkillRow(int stat, boolean action) {
        TableRow row;

        if (action) {
            switch (stat) {
            case Info.ST:
                row = (TableRow) mStatStSkillTable.getChildAt(mStatStSkillTable
                        .getChildCount() - 1);

                mMainSecondStLastSkillEdit = (EditText) row.getChildAt(0);
                mMainSecondStLastLvlEdit = (EditText) row.getChildAt(1);
                mMainSecondStLastRelEdit = (EditText) row.getChildAt(2);
                mMainSecondStLastCostEdit = (EditText) row.getChildAt(3);

                break;
            case Info.DX:
                break;
            case Info.IQ:
                break;
            case Info.HT:
            }
        }
    }

    private void addSkillRow(int stat) {
        int skillCount;
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        TableRow row = (TableRow) inflater.inflate(
                R.layout.activity_main_skill_row, null);

        switch (stat) {
        case Info.ST:
            skillCount = mStatStSkillTable.getChildCount();
            if (skillCount > 0)
                mStatStSkillTable.addView(row, skillCount - 1);
            else
                mStatStSkillTable.addView(row);
            break;
        case Info.DX:
            skillCount = mStatDxSkillTable.getChildCount();
            if (skillCount > 0)
                mStatDxSkillTable.addView(row, skillCount - 1);
            else
                mStatDxSkillTable.addView(row);
            break;
        case Info.IQ:
            skillCount = mStatIqSkillTable.getChildCount();
            if (skillCount > 0)
                mStatIqSkillTable.addView(row, skillCount - 1);
            else
                mStatIqSkillTable.addView(row);
            break;
        case Info.HT:
            skillCount = mStatHtSkillTable.getChildCount();
            if (skillCount > 0)
                mStatHtSkillTable.addView(row, skillCount - 1);
            else
                mStatHtSkillTable.addView(row);
        }

        updateSkillRow(stat, Info.ADD);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mMainTlCostEdit = (EditText) findViewById(R.id.main_tl_cost_edit);
        mMainTlCostEdit.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable s) {
                String text = mMainTlCostEdit.getText().toString();
                text = "[" + text + "]";
                mMainTlCostEdit.setText(text);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
            }

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

            }
        });
        // mMainTlCostEdit.setOnClickListener(new View.OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        // String text = mMainTlCostEdit.getText().toString();
        // text.replace("[", "");
        // text.replace("]", "");
        // mMainTlCostEdit.setText(text);
        // }
        // });

        mStatStSkillTable = (TableLayout) findViewById(R.id.main_second_st_skills_tablelayout);
        addSkillRow(Info.ST);
        mMainSecondStLastSkillEdit.addTextChangedListener(new TextWatcher() {

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

            }

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

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                String text = mMainSecondStLastSkillEdit.getText().toString();
                if (text == "") {

                } else {
                    addSkillRow(Info.ST);
                }
            }
        });

        mStatDxSkillTable = (TableLayout) findViewById(R.id.main_second_dx_skills_tablelayout);
        mStatIqSkillTable = (TableLayout) findViewById(R.id.main_second_iq_skills_tablelayout);
        mStatHtSkillTable = (TableLayout) findViewById(R.id.main_second_ht_skills_tablelayout);
        addSkillRow(Info.DX);
        addSkillRow(Info.IQ);
        addSkillRow(Info.HT);

        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                this, R.array.damage_table_array, R.layout.my_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mMainThirdSecondaryDamageThrustSpinner = (Spinner) findViewById(R.id.main_third_secondary_damage_thrust_spinner);
        mMainThirdSecondaryDamageThrustSpinner.setAdapter(adapter);
        mMainThirdSecondaryDamageThrustSpinner.setSelection(4);
        mMainThirdSecondaryDamageSwingSpinner = (Spinner) findViewById(R.id.main_third_secondary_damage_swing_spinner);
        mMainThirdSecondaryDamageSwingSpinner.setAdapter(adapter);
        mMainThirdSecondaryDamageSwingSpinner.setSelection(6);
        mMainThirdSecondaryEncumbranceSpinner = (Spinner) findViewById(R.id.main_third_secondary_enchumbrance_spinner);
        adapter = ArrayAdapter.createFromResource(this,
                R.array.encumbrance_level_array, R.layout.my_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mMainThirdSecondaryEncumbranceSpinner.setAdapter(adapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_item_extras:
            Intent extrasIntent = new Intent(MainActivity.this,
                    ExtraActivity.class);
            startActivity(extrasIntent);
            return true;
        case R.id.menu_item_equipment:
            Intent equipmentIntent = new Intent(MainActivity.this,
                    EquipmentActivity.class);
            startActivity(equipmentIntent);
            return true;
        case R.id.menu_item_items:
            Intent itemsIntent = new Intent(MainActivity.this,
                    ItemActivity.class);
            startActivity(itemsIntent);
            return true;
        case R.id.menu_item_options:
            Intent optionsIntent = new Intent(MainActivity.this,
                    OptionListActivity.class);
            startActivity(optionsIntent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

}

2 个答案:

答案 0 :(得分:0)

你可以这样做:

String temp = EditText.getText().toString();
temp="[temp]";
EditText="[]";

或者您希望它在EditText中显示? 您可以使用OnKeyListener并在按下某个键后使EditText看起来像您想要的那样。 例如“ENTER”

EditText=.setText("[temp]");

答案 1 :(得分:0)

View.OnFocusChangeListener上使用EditText。它包含onFocusChange方法,该方法在视图上的焦点状态更改时调用。对于这种情况,您可以在EditText失焦后设置文本周围的大括号,并将其添加回EditText获得焦点。

mMainTlCostEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            String text = mMainTlCostEdit.getText().toString();
            mMainTlCostEdit.setText(text.substring(1, text.length() - 1));
        } else {
            mMainTlCostEdit.setText(String.format("[%s]", mMainTlCostEdit.getText().toString()));
        }
    }
});

有关更多参考,请参阅Android开发者页面上的此文档 - https://developer.android.com/reference/android/view/View.OnFocusChangeListener.html