D
D
DenisE342016-12-17 00:39:49
Java
DenisE34, 2016-12-17 00:39:49

How to assign an id to list items?

I want to open a new activity when I click on a list item.
The list is formed like this:

for (int i = 0; i < name.length; i++) {
      Log.d("myLogs", "i = " + i);
      View item = ltInflater.inflate(R.layout.item, linLayout, false);
      TextView tvName = (TextView) item.findViewById(R.id.tvName);
      tvName.setText(name[i]);
      TextView tvPosition = (TextView) item.findViewById(R.id.tvPosition);
      tvPosition.setText("Должность: " + position[i]);
      TextView tvSalary = (TextView) item.findViewById(R.id.tvSalary);
      tvSalary.setText("Оклад: " + String.valueOf(salary[i]));
      item.getLayoutParams().width = LayoutParams.MATCH_PARENT;
      item.setId(i+1);
      item.setOnClickListener(this);
      item.setBackgroundColor(colors[i % 2]);
      linLayout.addView(item);
    }
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.1:
      Intent intent = new Intent(this, ActivityTwo.class);
  startActivity(intent);
      break;
    default:
      break;
    }
  }

It turns out that the first TextView is assigned id 1. But, idea says that there is an error in the case R.id.1: line. However, the code is working. If instead of 1 you put another id assigned manually, not in a loop, then everything works. Ids are also assigned, I tried to display them through println () - everything works. So how to work out clicking on id?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question