简体   繁体   中英

How to change text in an EditText before and after typing

I have an EditText that by default has this string in it "[ ]". What I want is that when the user selects the EditText the brackets and space all disappear. Then after they are done editing I would like to place the brackets around their edit.

So, for example, if they typed "123" then when they are done typing the EditText will show "[123]".

I tried following the answer here, EditText not updated after text changed in the TextWatcher , by doing setText on the EditText from the afterTextChanged, but that throws an error.

Thanks for any help.

Here's my code: I just added the xml that creates the first line of the program since that's the line I'm having problems with.

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);
        }
    }

}

you can do somthing like:

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

or do you want it to be showed inside the EditText? you can use OnKeyListener and make the EditText look like you want after some key is pressed.. eg "ENTER"

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

Use a View.OnFocusChangeListener on the EditText . It contains the onFocusChange method which is called when the focus state on the view is changed. For this case, you can set the braces surrounding the text once the EditText goes out of focus and add those back upon the EditText gaining focus.

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()));
        }
    }
});

For more reference, check out this documentation on the Android Developers page - https://developer.android.com/reference/android/view/View.OnFocusChangeListener.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM