Change layout of selected list item in Android

前端 未结 1 630
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-12 23:14

I need to create a ListView and show more detailed layout only for the selected row in order to show more information to the costumer. What I tried is below:

相关标签:
1条回答
  • 2021-01-12 23:49

    What you are doing is not even gonna change the View of the ListView Item, you are inflating an unknown view.

    solution:

    create a method in your adapter for setting the position of the selected item:

    public void selectedItem(int position)
    {
       this.position = position; //position must be a global variable
    }
    

    in your getView inflate the view when the position is equals to the click item position

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    
        ViewHolder holder = null;
    
        LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.listitem_news, null);
            holder = new ViewHolder();
    
            holder.title = (TextView) convertView.findViewById(R.id.title);
            holder.image = (ImageView) convertView.findViewById(R.id.imageView1);            
    
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
    
        NewsData news = items.get(position);
    
        holder.title.setText(news.getTitle());
        new DownloadImageTask(holder.image).execute(news.getImgUrl());
    
        if(this.position == position)
        {
            view2 = mInflater.inflate(R.layout.listitem_news_selected, null);
            TextView info = (TextView) view2.findViewById(R.id.info);
    
            info.setText(news.getInfo());
    
            return view2;
        }
    
    
        return convertView;
    }
    

    Using it in your onItemClick

    NewsListAdapter adapter = new NewsListAdapter(this, news);
    newsListView.setAdapter(adapter );
    newsListView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    
              adapter.selectedItem(position);
              adapter.notifyDataSetChange();
        }
    });
    

    always have a reference/object to your adapter so you can refresh your listView upon clicking on it.

    0 讨论(0)
提交回复
热议问题