activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" 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="com.example.edittextdemo1.MainActivity" > <EditText android:id="@+id/edittext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" /> <Button android:id="@+id/button" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="添加QQ表情" /> </LinearLayout>
MainActivity.java:
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.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity implements OnClickListener { 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.button); button.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub int randomId = 1 + new Random().nextInt(9); try { Field field = R.drawable.class.getDeclaredField("qq" + randomId); int resourceId = Integer.parseInt(field.get(null).toString()); // 在Android中要显示图片信息,必须使用Bitmap位图的对象来装载 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resourceId); ImageSpan imageSpan = new ImageSpan(MainActivity.this, bitmap); SpannableString spannableString = new SpannableString("qq"); spannableString.setSpan(imageSpan, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); editText.append(spannableString); } catch (Exception e) { // TODO: handle exception } } }
时间: 2024-10-23 18:13:17