Получить идентификатор элемента из списка при нажатии Android Studio - PullRequest
0 голосов
/ 07 сентября 2018

Я создаю приложение календаря, которое показывает список, если дата получила событие от json web, Я хочу показать детали события в другом действии, когда происходит щелчок по событию в списке, но каждый раз, когда я щелкаю элемент, TextView отображает позицию элемента, а не идентификатор элемента

Мой код OnItemClickListener

list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            /*Uri test = Uri.parse("tel:3154431");
            Intent intentPhone = new Intent(Intent.ACTION_DIAL, test);
            startActivity(intentPhone);*/
            Intent i = new Intent(getApplicationContext(), DetailList.class);
            i.putExtra("id", id);
            startActivity(i);
        }
    });

Код моего адаптера

public class CustomAdapter extends BaseAdapter {
     Context exContext;
     int list_item;
     private final LayoutInflater inflater;
     ArrayList<ScheduleInfo> scheduleInfo;
     ProdiInfo prodiInfo;
     MarketingActionsInfo marketingActionsInfo;
     ProdiNameInfo prodiNameInfo;
     UniversityInfo universityInfo;

     public CustomAdapter(Context mContext) {
          this.exContext = mContext;
          inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
     }
     public void  updateData(ArrayList<ScheduleInfo> scheduleInfo){
          this.scheduleInfo = scheduleInfo;
          notifyDataSetChanged();
     }

     @Override
     public int getCount() {
          return scheduleInfo.size();
     }

     @Override
     public Object getItem(int position) {
          return scheduleInfo.get(position);
     }

     @Override
     public long getItemId(int position) {
          return position;
     }

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
          if (convertView == null) {
               TextView action, studyProgram, universityName, time;
               convertView = inflater.inflate(R.layout.list_item, parent, false);
               action = (TextView) convertView.findViewById(R.id.marketing_action);
               studyProgram = (TextView) convertView.findViewById(R.id.studyprogram);
               universityName = (TextView) convertView.findViewById(R.id.univname);
               time = (TextView) convertView.findViewById(R.id.time);

               int id = (scheduleInfo.get(position).getSchedId());
               action.setText(scheduleInfo.get(position).getMarketingActionsInfo().getName());
               studyProgram.setText(scheduleInfo.get(position).getProdiInfo().getProdiNameInfo().getProdiName());
               universityName.setText(scheduleInfo.get(position).getProdiInfo().getUniversityInfo().getUnivName());
               time.setText(scheduleInfo.get(position).getStartDate()+" - "+scheduleInfo.get(position).getEndDate());
          }
          return convertView;
     }
}

и вот мой код DetailActivity

public class DetailList extends AppCompatActivity {

     @Override
     protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_detail_list);
          TextView idTest1 = (TextView)findViewById(R.id.schID);
          Intent in = getIntent();
          Bundle b = in.getExtras();
          if (b!=null){
              String j = (String) b.get("id").toString();
              idTest1.setText(j);
          }
     }
}

Ответы [ 4 ]

0 голосов
/ 07 сентября 2018
list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

           Bundle bundle = new Bundle();
           Intent i = new Intent(getApplicationContext(), DetailList.class);
           bundle.putLong("id",id);
           i.putExtras(bundle);
           startActivity(i)
        }
    });

и в DetailList.class получите значение пакета, как это

   try {
       Intent in = getIntent();
       Bundle b = in.getExtras();
       long id= b.getLong("id");
    } catch (Exception e) {
           e.printStackTrace();
   }
0 голосов
/ 07 сентября 2018

Вы можете поместить один TextView (скажем, идентификатором этого TextView является tvMyId) в строку настраиваемого списка и установить его видимость пропавшим. При заполнении данных в адаптере установите идентификатор для этого текстового просмотра и получите идентификатор следующим образом

  @Override
      public View getView(int position, View convertView, ViewGroup parent) {
              if (convertView == null) {
                //add this line
                 TextView tvMyId = convertTView.findViewById(R.id.tvMyId).

                   TextView action, studyProgram, universityName, time;
                   convertView = inflater.inflate(R.layout.list_item, parent, false);
                   action = (TextView) convertView.findViewById(R.id.marketing_action);
                   studyProgram = (TextView) convertView.findViewById(R.id.studyprogram);
                   universityName = (TextView) convertView.findViewById(R.id.univname);
                   time = (TextView) convertView.findViewById(R.id.time);

                //   int id = (scheduleInfo.get(position).getSchedId());
                   tvMyId.setText(scheduleInfo.get(position).getSchedId()); //and add this line
                   action.setText(scheduleInfo.get(position).getMarketingActionsInfo().getName());
                   studyProgram.setText(scheduleInfo.get(position).getProdiInfo().getProdiNameInfo().getProdiName());
                   universityName.setText(scheduleInfo.get(position).getProdiInfo().getUniversityInfo().getUnivName());
                   time.setText(scheduleInfo.get(position).getStartDate()+" - "+scheduleInfo.get(position).getEndDate());
              }
              return convertView;
         }

ItemClickListener

list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TextView tv = view.findViewById(R.id.tvMyId);
            String myId = tv.getString().toString();
            Intent i = new Intent(getApplicationContext(), DetailList.class);
            i.putExtra("id", myId);
            startActivity(i);
        }
    });
0 голосов
/ 07 сентября 2018

Что бы мы ни возвращали из getItemId () Adapter, это то, что мы получаем в onItemClick (родительский объект AdapterView, представление View, позиция int, длинный идентификатор). В вашем случае вы проходите «позицию». Итак, вы получаете то же самое в «id». Поэтому, пожалуйста, измените его в соответствии с вашими потребностями.

     @Override
     public long getItemId(int position) {
          return position;
     }

list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
0 голосов
/ 07 сентября 2018

Проблема в том, что вы отправляете длинные лишние и пытаетесь получить пакет на другой стороне. Измените ваш код, как показано ниже:

list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        /*Uri test = Uri.parse("tel:3154431");
        Intent intentPhone = new Intent(Intent.ACTION_DIAL, test);
        startActivity(intentPhone);*/
        Intent i = new Intent(getApplicationContext(), DetailList.class);
        Bundle bundle = new Bundle();
        bundle.putLong("id",id);
        i.putExtras(bundle);
        startActivity(i);
    }
});
...