olirwin
olirwin

Reputation: 605

How to add a variable number of TextViews and EditViews in activity

I'm currently trying to add a user-defined number of TextViews and EditText to an activity, but can't seem to do it other than hard-coding it by creating a variety of different activities.

The objective of this activity is to take the names of the players, the number of which is relayed by the intent extra from the preceding activity.

I'm trying to add both a TextView saying "Player X: " and an EditText to type the name of the player for each player

I know from this post: How to create a variable number of textviews in android that I have to do this programmatically, however, it does not seem to work for me (the activity remains blank when tested)

I have tried creating a temp LinearLayout to which I add the two views in a for(), still nothing.

Any ideas? Am I on the right track?

Best regards

[EDIT] Code is here :

public class players extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_players);

    Bundle extras = new Bundle();
    final int numPlayers = extras.getInt("num");
    final LinearLayout myLayout = findViewById(R.id.lin_Re);
    final ArrayList<Player> players = new ArrayList<>();



    int size = numPlayers; // total number of TextViews to add

    TextView[] tv = new TextView[size];
    TextView temp;
    EditText[] et = new EditText[size];
    EditText temp2;
    LinearLayout temp3;

    for (int i = 0; i < size; i++)
    {
        temp = new TextView(this);
        temp2 = new EditText(this);
        temp3 = new LinearLayout(this);

        temp.setText("Player " + i + " : "); //arbitrary task

        // add the textview to the linearlayout
        temp3.addView(temp);
        temp3.addView(temp2);

        tv[i] = temp;
        et[i] = temp2;

        myLayout.addView(temp3);
    }


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:id="@+id/lin_Re">



    </LinearLayout>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b_send"/>

</LinearLayout>

Upvotes: 2

Views: 775

Answers (1)

Tuấn Kiệt
Tuấn Kiệt

Reputation: 310

There is 2 way to achieve this:
1. Use a RecyclerView [Recommended]
2. Add TextView and EditText ( which is nested in a Horizontal LinearLayout) into a Vertical LinearLayout nested in a ScrollView programmatically

The first solution I describe below is quite simple if you're familiar with RecyclerView or ListView, the second solution (your current track) is a bit tricky but still achievable.

Solution 1:
enter image description here
enter image description here
enter image description here

MainActivity

public class MainActivity extends AppCompatActivity {

    RecyclerView mPlayerList;
    List<String> mPlayerNames;
    PlayerAdapter mAdapter;
    EditText mInput;
    Button mCreateButton;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPlayerNames = new ArrayList<>();

        // setup recycler view
        mPlayerList = findViewById(R.id.player_list);
        mPlayerList.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new PlayerAdapter();
        mPlayerList.setAdapter(mAdapter);

        // setup input EditText
        mInput = findViewById(R.id.input);

        // setup Create button
        mCreateButton = findViewById(R.id.create_button);
        mCreateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // clear old player names
                mPlayerNames.clear();

                // read user input: number of player:
                String input = mInput.getText().toString();
                int numberOfPlayer;
                try {
                    numberOfPlayer = Integer.parseInt(input);
                } catch (NumberFormatException e) {
                    Toast.makeText(MainActivity.this, "Invalid input!!!", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < numberOfPlayer; ++i) {
                    mPlayerNames.add("Player #" + (i + 1));
                }

                // make change on recycler view
                mAdapter.notifyDataSetChanged();

                // dismiss keyboard
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mInput.getWindowToken(), 0);

            }
        });
    }

    private class PlayerAdapter extends RecyclerView.Adapter<PlayerAdapter.PlayerHolder> {


        @Override
        public PlayerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(MainActivity.this).inflate(R.layout.item_layout, parent, false);
            return new PlayerHolder(v);
        }


        @Override
        public void onBindViewHolder(PlayerHolder holder, int position) {
            holder.bind(mPlayerNames.get(position));
        }

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

        public class PlayerHolder extends RecyclerView.ViewHolder {

            TextView mPlayerLabel;
            EditText mPlayerName;


            public PlayerHolder(View itemView) {
                super(itemView);
                mPlayerLabel = itemView.findViewById(R.id.player_label);
                mPlayerName = itemView.findViewById(R.id.player_name);
            }

            public void bind(String playerName) {
                mPlayerLabel.setText(playerName);
                mPlayerName.setHint("Name of " + playerName);
            }
        }
    }
}

The sample project can be found here:
https://github.com/raiytu4/stackcase004

Upvotes: 3

Related Questions