android布局添加布局,Android中添加布局和初始化布局总结

本文总结了Android中布局添加的四种形式。一是在Activity的onCreate()方法中添加;二是在适配器中用View.inflate()或LayoutInflater.from(Context).inflate()方法加载;三是写方法创建view对象;四是自定义布局,继承并重写系统view方法后引用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在android中布局很重要,下面总结下布局的三种形式

①.在Activity的onCreate()方法中进行添加比如:setContentView(R.layout.activity_main);

②此种情况多用在适配器中进行加载,如下:

一种方法是用View.inflate()方法;

代码说明:前提是自定义了一个参数:private Context context;

@override代码是自定义一个适配器CalendarAdapter extends BaseAdapter中的getView()方法中来添加一个自定义的布局

calendar_cell_layout.xml.

@Override

public View getView(int position, View convertView, ViewGroup parent) {

// TODO Auto-generated method stub

ViewHolder holder = null;

if (convertView == null) {

convertView = View.inflate(context,R.layout.calendar_cell_layout,null);

holder = new ViewHolder();

holder.dayTextView = (TextView)convertView.findViewById(R.id.jkdayid);

holder.dayNLTextView = (TextView)convertView.findViewById(R.id.jkday_nlid);

holder.isdataImageView = (ImageView)convertView.findViewById(R.id.isdataid);

convertView.setTag(holder);

} else {

holder = (ViewHolder) convertView.getTag();

}

public class ViewHolder {

public TextView dayTextView;

public TextView dayNLTextView;

public ImageView isdataImageView;

}

另外一种形式如下:用LayoutInflater.from(Context).inflate()方法。

代码说明:是一个自定义的 class DeviceListAdapter extends BaseAdapter中的override的getView()方法。

@Override

public View getView(int position, View convertView, ViewGroup parent) {

if (convertView == null) {

convertView = LayoutInflater.from(MainActivity.this).inflate(

R.layout.list_bluetooth_item, null);

viewHolder = new ViewHolder();

viewHolder.tv_devName = (TextView) convertView

.findViewById(R.id.tv_blueth_name);

viewHolder.tv_devAddress = (TextView) convertView

.findViewById(R.id.tv_blueth_location);

viewHolder.tv_devStatus=(TextView)convertView.findViewById(R.id.tv_blueth_status);

convertView.setTag(viewHolder);

} else {

convertView.getTag();

}

}

}

class ViewHolder {

TextView tv_devName, tv_devAddress,tv_devStatus;

}

③写一个简单的方法来创建一个view对象:

private View initView() {

// TODO Auto-generated method stub

TextView textView = new TextView(this);

textView.setText("title");

textView.setTextSize(20);

textView.setTextColor(Color.RED);

textView.setGravity(Gravity.CENTER);

LinearLayout ll = new LinearLayout(this);

LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,

LayoutParams.MATCH_PARENT);

ll.setBackgroundColor(Color.WHITE);

ll.addView(textView, params);

return ll;

}

④在对各种布局都熟悉的情况下,采用自定义布局,对android系统提供的view进行继承,重写其中的方法,达到想要的效果后,然后在需要的地方进行引用。

以上均来自个人总结,如有不妥当之处,还烦请各位编程爱好者批评指正,共同进步!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值