这两天写了一个小Demo,有一个功能就是聊天,然后涉及到了View的动态加载,下图就是动态加载后的效果
话不多说,直接上代码。
1、聊天界面的部分布局文件,使用ScrollView将聊天内容包裹起来,当内容超出界面显示时,可以上下滑动。
<ScrollView
android:id="@+id/chat_sl"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:id="@+id/chat_ll_content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
2、动态添加聊天内容
//message是消息内容
protected void sendContent(String message) {
RelativeLayout relativeLayout = new RelativeLayout(ChatActivity.this);
@SuppressWarnings("deprecation")
RelativeLayout.LayoutParams relatineParams = new RelativeLayout.LayoutParams(
LayoutParams.FILL_PARENT, dipToPx(70));
relativeLayout.setLayoutParams(relatineParams);
// 添加图像
ImageView photo = new ImageView(ChatActivity.this);
photo.setId(1000);
photo.setBackgroundResource(R.drawable.my);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
dipToPx(50), dipToPx(50));
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.CENTER_VERTICAL);
params.rightMargin = dipToPx(10);
photo.setLayoutParams(params);
// 添加消息内容
TextView content = new TextView(ChatActivity.this);
content.setBackgroundResource(R.drawable.message_right);
content.setText(message);
content.setTextSize(15);
content.setPadding(dipToPx(10), 0, dipToPx(10), 0);
content.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, dipToPx(50));
params2.leftMargin = dipToPx(10);
params2.addRule(RelativeLayout.CENTER_VERTICAL);
params2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params2.rightMargin = dipToPx(70);
content.setLayoutParams(params2);
relativeLayout.addView(photo, params);
relativeLayout.addView(content, params2);
ll_message2.addView(relativeLayout);
}
3、dipToPx(float)是根据手机分辨率将dp转换成px,因为在java代码中设置的属性基本上都是以px未单位的,而xml文件一般都是以dp为单位的。
// 将dp转换成px
public int dipToPx(float dp) {
//得到当前手机dp转px的转换率
float px = getResources().getDisplayMetrics().density;
return (int) (dp * px + 0.5f);
}