敏感词汇通常会在后台进行判断,但偶尔也会有在前端进行判断,其实很简单,就是对一个字符串中特定字符的替换。
布局代码:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="visahall.cn.xiaoxin.MainActivity"> <Button android:id="@+id/btn" android:text="点击确定把EditText中的字显示在TextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentStart="true" /> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" android:layout_below="@+id/btn" android:layout_centerHorizontal="true" android:layout_marginTop="196dp" /> <EditText android:id="@+id/edit" android:hint="敏感字为 美国, 西班牙, 德玛西亚" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/btn" android:layout_alignParentStart="true" /> </RelativeLayout>
MainActivity:
1.public class MainActivity extends AppCompatActivity { private Button button; private EditText editText; private TextView textView; private List<String> list = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String aa = String.valueOf(editText.getText()); for (int i = 0; i < list.size(); i++) { String x = list.get(i); //x为敏感词汇 if (aa.contains(x)){ aa = aa.replaceAll(x, getXing(x)); } } textView.setText(aa); } }); } private void init() { button = (Button) findViewById(R.id.btn); editText = (EditText) findViewById(R.id.edit); textView = (TextView) findViewById(R.id.text); list.add("国家级"); list.add("第一"); list.add("史上"); list.add("垃圾"); } //得到"*"的数量,然后进行替换相应的字符串 private String getXing(String f){ String a = ""; for (int i = 0; i < f.length(); i++) { a = a + "*"; } return a; } }