Android表格控件动态生成表格

表格是很常用的控件,Android本身提供了TableLayout供布局实现。但本文介绍另外一种思路,用动态布局的方式实现,这种方式更灵活,内容、样式能高度扩展,熟练的人可随意运用到任何视图复用的场景。使用滚动条避免显示不完全问题。

效果图:

Android表格控件动态生成表格_第1张图片

核心代码如下:

public class DriveRecordAcivity extends Fragment{
	private View view = null;
	private LinearLayout  wr_areas;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view=inflater.inflate(R.layout.driverecord_activity, null);
		wr_areas=(LinearLayout) view.findViewById(R.id.wr_areas);
		if(ApplicationUtils.getCheckedFcRecord(new DBAdapter(view.getContext()))!=null){
			 List titleData=ApplicationUtils.getCheckedFcRecord(new DBAdapter(view.getContext()));
			 showData(titleData);
		}
		return view;
	}

	/**
	 * 发车数据动态添加状态
	 */
	private void showData(List titleData) {
		for (int i = 0; i < titleData.size(); i++) {
			final CheckedFcRecord pojo = titleData.get(i);
			LinearLayout llWashingRoomItem = new LinearLayout(view.getContext());
			llWashingRoomItem.setLayoutParams(new RelativeLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			llWashingRoomItem = (LinearLayout) getActivity().getLayoutInflater().inflate(R.layout.checkedfcrecord_template, null);
			TextView time = (TextView) llWashingRoomItem.findViewById(R.id.time);
			TextView vhclNo = (TextView) llWashingRoomItem.findViewById(R.id.vhclNo);
			TextView jpy = (TextView) llWashingRoomItem.findViewById(R.id.jpy);
			TextView ticket = (TextView) llWashingRoomItem.findViewById(R.id.ticket);
			time.setText(DateTools.getStringFromDate(pojo.getFcTime(),null));
			vhclNo.setText(pojo.getVhcl_no());
			jpy.setText(pojo.getJsy_name());
			//Integer类型需要转换用.toString()不然报错
			ticket.setText(pojo.getJps().toString());
			//动态设置layout_weight权重设置表格宽度
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1.6f);  
			time.setLayoutParams(lp);  
			lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);  
			vhclNo.setLayoutParams(lp);  
			lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.8f);  
			jpy.setLayoutParams(lp);  
			lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.8f);  
			ticket.setLayoutParams(lp);  
			wr_areas.addView(llWashingRoomItem);
		}
	}
}

上面是运用到项目中,动态获取数据。测试源码中的是手动添加的数据。

xml布局如下:


   
        
    

    

    

        

        

        

         
        
        

         
        
        
    

    

    

        
        
    

Android表格控件动态生成表格_第2张图片

定义可重用的视图部分,xml文件如下:




    

        

        
	
        
                
		
				
        

        
                
        
        
        

    

    

 

Android表格控件动态生成表格_第3张图片

最后附上源码Eclipse版本:
点击下载

你可能感兴趣的:(Android)