1. 程式人生 > >EditText實現輸入自定義表情

EditText實現輸入自定義表情

本文例項講述了Android程式設計開發之EditText實現輸入QQ表情影象的方法。分享給大家供大家參考,具體如下:

實現效果如下:

將QQ表情影象放到res下的drawable-hdpi資料夾下:

佈局檔案:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<EditText

android:id="@+id/edittext"

android:layout_width

="fill_parent"

android:layout_height="wrap_content"

android:layout_marginTop="10dp"

android:inputType="text">

</EditText>

<Button

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignLeft="@+id/edittext"

android:layout_alignRight="@+id/edittext"

android:layout_below="@+id/edittext"

android:layout_marginTop="38dp"

android:text="新增QQ表情" />

MainActivity.java:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

package com.example.edittext1;

import java.lang.reflect.Field;

import java.util.Random;

import android.app.Activity;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Bundle;

import android.text.Spannable;

import android.text.SpannableString;

import android.text.style.ImageSpan;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

public class MainActivity extends Activity {

//宣告控制元件物件

private EditText editText;

private Button button;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

editText=(EditText) findViewById(R.id.edittext);

button=(Button) findViewById(R.id.button1);

//為按鈕註冊點選事件

button.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

//產生隨機數 隨機數是從0開始,所以要加1,這樣就會產生1到9的隨機數

int randomId=1+new Random().nextInt(9);

try {

//獲取表情圖片檔名

Field field=R.drawable.class.getDeclaredField("face"+randomId);

int resourceId = Integer.parseInt(field.get(null).toString());

// 在android中要顯示圖片資訊,必須使用Bitmap點陣圖的物件來裝載

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId);

//要讓圖片替代指定的文字就要用ImageSpan

ImageSpan imageSpan = new ImageSpan(MainActivity.this, bitmap);

SpannableString spannableString = new SpannableString("face");//face就是圖片的字首名

spannableString.setSpan(imageSpan, 0, 4,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

editText.append(spannableString);

} catch ( Exception e) {

}

}

});

}

@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;

}

}

希望本文所述對大家Android程式設計有所幫助。