如何在edittext

时间:2018-03-01 16:29:45

标签: android android-studio android-recyclerview recycler-adapter

我希望通过RecyclerView显示我从用户那里获得的EditText数据。我怎么能这样做?

代码:

public class MyRecyler extends RecyclerView.Adapter<MyRecyler.MyHolder> {
    Context context;
    String names;

    public MyRecyler(Context context, String names) {
        this.context = context;
        this.names = names;
    }

    @Override
    public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(this.context);
        View view = inflater.inflate(R.layout.names, parent, false);
        return new MyHolder(view);
    }

    @Override
    public void onBindViewHolder(MyHolder holder, int position) {
        holder.name.setText(this.names.indexOf(position));
    }

    @Override
    public int getItemCount() {
        return this.names.length();
    }

    public class MyHolder extends RecyclerView.ViewHolder {
        TextView name;

        public MyHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.name);
        }
    }
}

    public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    EditText editText;
    Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.recyclerView);
        editText = findViewById(R.id.editText);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyRecyler obj = new MyRecyler(this,editText.getText().toString());
                recyclerView.setAdapter(obj);
                recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
            }
        });


    }
}

1 个答案:

答案 0 :(得分:0)

首先使用arraylist来存储你的字符串。

ArrayList<String> names = new ArrayList<String>()
names.add("name1")
names.add("name2")
names.add("name3")

YourAdapter adapter = new Adapter(this, names)
rView.setAdapter(adapter)

将此arraylist传递给您的recyclerview

假设您有一个项目列表来显示recyclerview上的数据。首先获取项目列表的大小,然后使用以下函数插入您的值。

public int getItemCount() {
    return itemList.size();
}

插入项目作为recyclerview的最后一项

 public void add(MODEL object) {
    itemList.add(object);
    notifyItemInserted(getItemCount() - 1);
}

将项目插入您指定的位置。

public void add(int position, MODEL object) {
    itemList.add(position, object);
    notifyItemInserted(position);
}

notifyiteminserted()将通知回收者视图,显示有新数据。

作为一个例子

String str = editext.getText().toString()
//ur_model = the model you used in your recycler view
// setName(str) is a setter function which will set the str
ur_model.setName(str)
// Passing your model and updating the recyclerview
adapter.add(ur_model)