Frage

        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);}`

Here , I want to use my RelativeLayout that I have created programmatically in place of R.layout.row_ten_words

Code that I want to use is:

          ` 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);`

I am totally new to android but know JAVA well. Please suggest me something if I am wrong in my approach.

Thanks in advance.

War es hilfreich?

Lösung

You are essentially replacing the inflation of a View with your dynamic View creation. To create a View programmatically, you need a Context reference. You will need to add a class member and set it in the Adapter's constructor (this may not be exactly like yours, but you get the idea):

Context context;

public SomeAdapter(Context context, int resource)
{
    super(context, resource);

    this.context = context;
    ...
    ...

And then:

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;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top