使用EditText更改URL的一部分

时间:2014-01-02 23:55:15

标签: java android string

我有一个EditText字段,下面有一个按钮指向一个URL。

例如:

https://www.google.com/#q=cool&safe=off

我使用什么代码,以便每当我输入EditText字段时,它会将URL中的单词cool更改为其他单词?

3 个答案:

答案 0 :(得分:0)

这样做的一种方法是在按钮的onClick方法中重新生成url。所以它会是这样的:

String word = edittext.getText().toString();
String url = "https://www.google.com/#q=" + word + "&safe=off";

答案 1 :(得分:0)

您可以使用以下内容:

OnClick(View v, ...)
    switch(v.getId()){
        case R.id.your_button:
            updateEditText();
            break;
    }
}

void updateEditText(){
    // mEditText is your edit text on the activity
    String temp = mEditText.getText().toString();
    temp.replace("cool","your new word");
    mEditText.setText(temp);
}

刚刚在记事本中做了这个,所以它可能在语法上不正确,但你明白了......

答案 2 :(得分:0)

您可以在EditText上使用textChanged侦听器。您应该在onCreate方法中实现此功能:

final EditText et = (EditText)findViewById(R.id.editText);
et.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) 
    {
        // these three lines are OPTIONAL
        int selection = et.getSelectionStart(); // get where the cursor was
        boolean atEnd = false;
        if (selection == et.length()) atEnd = true; // cursor was at end of text

        String text = et.getText().toString();
        if (text.contains("cool")) { // if EditText contains "cool"
            text = text.replace("cool", "newWord"); // replace it
            et.setText(text); // set the EditText to be the replaced String
        }

        // these two lines are OPTIONAL
        if (atEnd) et.setSelection(et.length()); // set cursor to end of text
        // set the cursor back to where it was
        else if (selection < et.length()) et.setSelection(selection);
    }

    @Override
    public void onTextChanged(CharSequence s, int st, int b, int c) 
    { }

    @Override
    public void beforeTextChanged(CharSequence s, int st, int c, int a) 
    { }

});