如何从动态创建的视图中的EditText获取文本

时间:2018-06-27 19:51:12

标签: android

所以我有一个带有Add按钮的垂直LinearLayout,每次单击它都会添加一个具有我自定义布局的视图,该视图具有2个textViews和2个editText。 TextView询问用户X和Y的位置,我要做的是从EditTexts获取输入,并在另一个TextView中逐行显示它,但是我的问题是我不知道如何获取文本从这些EditText。谁能帮我从这些EditText中获取文本,或者有人对实现此目标的更好方法提出建议?

LinearLayout parentLinearLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_holes);
    parentLinearLayout = findViewById(R.id.parentLinearLayout);
}

public void onAddField(View v){
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.field, null);

    parentLinearLayout.addView(rowView, + 1);


}

这是我到目前为止的代码。到目前为止,我从添加并完成按钮开始,当您单击添加时,它会添加我创建的布局。

field.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <TextView
        android:id="@+id/textViewX"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="X"
        android:textSize="18sp" />

    <EditText
        android:id="@+id/editTextX"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:ems="10"
        android:inputType="textPersonName" />

    <TextView
        android:id="@+id/textViewY"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:gravity="center"
        android:text="Y"
        android:textSize="18sp" />

    <EditText
        android:id="@+id/editTextY"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:ems="10"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/removeButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="REMOVE" />


</LinearLayout>

3 个答案:

答案 0 :(得分:0)

一种方法是保留您已完成的所有“字段”的列表

private List<View> rowViews = new List<View>();

public void onAddField(View v){
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View rowView = inflater.inflate(R.layout.field, null);
    rowViews.add(rowView);
    parentLinearLayout.addView(rowView, + 1);

}

通过这种方式,您可以获得所有视图的列表,并且每个视图都有唯一的索引。然后获取文本就像EditText ed = rowViews.get(index).findViewById(R.id.editTextX); ed.getText();

一样简单

答案 1 :(得分:0)

请查看以下示例:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    EditText editText;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        Button button = findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText(editText.getText());
            }
        });
    }
}

尤其是该行:

textView.setText(editText.getText());

答案 2 :(得分:0)

建议: 使用 RecyclcerView 而不是LinearLayout来添加动态视图,这很容易。

对于RecyclcerView,您需要创建一个适配器类来定义一个addItem方法来添加视图,并且可以轻松地从EditText获取文本。

看起来像这样:

import android.app.Activity;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.salesappdemo.R;
import com.salesappdemo.interfaces.RecyclerClickListener;
import com.salesappdemo.model.TaskModel;
import com.salesappdemo.utils.LogUtil;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Jaydip on 6/28/2018.
 */

public class FormAdapter extends RecyclerView.Adapter<FormAdapter.ViewHolder> {

    private static final String TAG = "FormAdapter";

    private Context context;
    private ArrayList<TaskModel> arrayList;
    private RecyclerClickListener clickListener;

    public FormAdapter(Activity context, ArrayList<TaskModel> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_form, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(v, new CustomEditTextListener());
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position) {

        //Set Data
        TaskModel model = arrayList.get(position);

        viewHolder.customEditTextListener.updatePosition(viewHolder.getAdapterPosition());
        viewHolder.edtTaskName.setText(model.getTaskName());

    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    @Override
    public int getItemViewType(int position) {
        return position;
    }

    //For Item Click Event
    public void setClickListener(RecyclerClickListener itemClickListener) {
        clickListener = itemClickListener;
    }

    public ArrayList<TaskModel> getList() {
        return arrayList;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.edtTaskName)
        EditText edtTaskName;
        @BindView(R.id.btnAdd)
        ImageView btnAdd;
        @BindView(R.id.btnDelete)
        ImageView btnDelete;
        @BindView(R.id.rlMain)
        RelativeLayout rlMain;

        public CustomEditTextListener customEditTextListener;

        public ViewHolder(View itemView, CustomEditTextListener customEditTextListener) {
            super(itemView);
            ButterKnife.bind(this, itemView);

            this.customEditTextListener = customEditTextListener;
            this.edtTaskName.addTextChangedListener(customEditTextListener);
        }

        @OnClick({R.id.btnAdd, R.id.btnDelete})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.btnAdd:
                    clickListener.onClickEvent(view, getAdapterPosition());
                    break;
                case R.id.btnDelete:
                    clickListener.onClickEvent(view, getAdapterPosition());
                    break;
            }
        }
    }

    private class CustomEditTextListener implements TextWatcher {
        private int position;

        public void updatePosition(int position) {
            this.position = position;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            if (arrayList != null) {
                arrayList.get(position).setTaskName(charSequence.toString());
                LogUtil.e(TAG, " :: onTextChanged :: position : " + position + "  Text : " + arrayList.get(position).getTaskName());
            }
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    }

    public void addItem(int position, TaskModel model) {
        if (arrayList != null) {
            arrayList.add(model);
            notifyItemInserted(position);
            LogUtil.e(TAG, " :: addItem :: Success :: position : " + position);
        }
    }

    public void remove(int position) {
        if (arrayList != null) {
            arrayList.remove(position);
            notifyItemRemoved(position);
            notifyItemRangeChanged(position, arrayList.size());
            LogUtil.e(TAG, " :: remove :: Success :: position : " + position);
        }
    }
}

然后从“活动”中添加和删除视图:

 @OnClick({R.id.btnAddTask})
    public void onViewClicked(View view) {

        switch (view.getId()) {

            case R.id.btnAddTask:

                LogUtil.e(TAG, " :: Clicked :: btnAddTask :: ");
                if (formAdapter != null) {
                    if (formAdapter.getList().size() == 0 ||
                            !TextUtils.isEmpty(formAdapter.getList().get(formAdapter.getList().size() - 1).getTaskName()))
                        formAdapter.addItem(formAdapter.getList().size(), new TaskModel());
                    else
                        Toast.makeText(this, "Enter a Task Name.", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

删除:

@Override
public void onClickEvent(View view, int position) {

    switch (view.getId()) {

        case R.id.btnDelete:

            if (formAdapter != null) {
                formAdapter.remove(position);
            }

            break;
    }

}