EditText是除了TextView控件之外的属性,还可以实现输入文本内容。
要实现功能:像QQ一样输入表情图像
效果图:
主要java代码:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
editText = (EditText)rootView.findViewById(R.id.edittext);
button = (Button)rootView.findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
int randomId = 1+new Random().nextInt(5);//随机数从开始,1-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 = new ImageSpan(getActivity(),bitmap);
SpannableString spannableString = new SpannableString("face");
spannableString.setSpan(imageSpan,0,4,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
editText.append(spannableString);
}catch(Exception e)
{
}
}
});
return rootView;
}
xml:
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<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:text="添加QQ表情"></Button>
</LinearLayout>
</ScrollView>
总结:
1.位图:在android中要显示图片信息,必须使用Bitmap位图的对象来装载
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),resourceId);
2.随机出现图片:
int randomId = 1+new Random().nextInt(5);//随机数从0开始,1-5
3.读代码能力增强