ViewHolder holder = null;
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.row_ten_words,null);
holder = new ViewHolder();
holder.txtSrc = (EditText) convertView.findViewById(R.id.txt_src_word);
holder.btnTranslate = (Button) convertView.findViewById(R.id.btn_translate);
holder.txtDes = (EditText) convertView.findViewById(R.id.txt_des_word);}`
在这里,我想使用我以编程方式创建的RelativeLayout代替R.layout.row_ten_words
我想使用的代码是:
` EditText txtSrc=new EditText(this);
EditText txtDes=new EditText(this);
Button btn_translate=new Button(this);
translate.setText("translate");
rl=new RelativeLayout(this);
rl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
rl.addView(txtSrc);
rl.addView(btn_translate);
rl.addView(txtDes);`
我对android很新,但很了解JAVA。如果我的方法不对,请建议我。
提前致谢。
答案 0 :(得分:0)
您实际上是用动态视图创建替换View的膨胀。要以编程方式创建View,您需要Context
引用。您将需要添加一个类成员并在Adapter的构造函数中设置它(这可能与您的完全不同,但您明白了):
Context context;
public SomeAdapter(Context context, int resource)
{
super(context, resource);
this.context = context;
...
...
然后:
if (convertView == null)
{
EditText txtSrc = new EditText(context);
EditText txtDes = new EditText(context);
Button btnTranslate = new Button(context);
btnTranslate.setText("translate");
rl = new RelativeLayout(context);
rl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
rl.addView(txtSrc);
rl.addView(btn_translate);
rl.addView(txtDes);
holder = new ViewHolder();
holder.txtSrc = txtSrc;
holder.btnTranslate = btnTranslate;
holder.txtDes = txtDes;
convertView = rl;
}