聊天内容的动态加载

          这两天写了一个小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);
	}


         

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值