ListView добавить столбцы программно - PullRequest
0 голосов
/ 04 мая 2020

Я создаю приложение для голосования с неизвестным количеством избирателей. Я хотел бы добавить столбцы в ListView, когда я знаю количество избирателей. Вот пример изображения: enter image description here

Есть ли способ динамического добавления столбцов в ListView? Я гуглил это в течение последних 2 часов и, похоже, не могу найти хорошего решения для этого.

У меня уже работает вертикальная и горизонтальная прокрутка, и я могу добавить имена избирателей сверху, но я могу не добавлять точки голосования динамически, так как они находятся внутри ListView.

Вот что я пробовал:

  1. Раздувать макет для ListView, чтобы добавлять элементы (по какой-то причине, если я добавил для пример «0», он добавил «0000» в первую строку и «00» в остальные строки)
  2. Использовать RecyclerView (он работал лучше, чем ListView, он правильно добавил «0», но для по какой-то причине ширина была не такой, как предполагалось

Ответы [ 2 ]

0 голосов
/ 04 мая 2020

Мне удалось сделать это с ListView, вот решение:

// Add profile names to topics
LinearLayout topicLayout = findViewById(R.id.topicLayout);
for (Profile p : selectedProfiles) {
    TextView name = (TextView) 
    getLayoutInflater().inflate(R.layout.result_voter_name,topicLayout, false);
    name.setText(p.getName());
    topicLayout.addView(name);
}

final ListView list = findViewById(R.id.resultItems);
ListAdapter adapter = new ListAdapter(this, selectedList.getItems(),
                    selectedProfiles);
list.setAdapter(adapter);
// List View adapter
public class ListAdapter extends BaseAdapter {

    private ArrayList<ListItem> listData;
    private ArrayList<Profile> profiles;
    private LayoutInflater layoutInflater;

    public ListAdapter(Context aContext, ArrayList<ListItem> listData, ArrayList<Profile> profiles) {
        this.listData = listData;
        this.profiles = profiles;
        layoutInflater = LayoutInflater.from(aContext);
    }

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

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = layoutInflater.inflate(R.layout.result_show_votes_item, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        ListItem item = listData.get(position);

        holder.name.setText(item.getName());
        holder.extra.setText(String.valueOf(item.getTotal()));

        // Loop through voters and update their given points
        for (int i = 0; i < profiles.size(); i++) {
            Profile profile = profiles.get(i);                  // Get profile
            TextView vote = holder.votePoints[i];               // Get textview for vote point
            int voteAmount = profile.votePointsOfItem(item);    // Get vote points amount for item
            vote.setText(voteAmount == 0 ? "" : String.valueOf(voteAmount));
        }

        return convertView;
    }

    /**
     * Class for holding view data.
     */
    class ViewHolder {
        View view;
        TextView name, extra;
        public TextView[] votePoints;

        /**
         * Holds all the necessary data for the view.
         * @param view convertview
         */
        public ViewHolder(View view) {
            this.view = view;
            name = view.findViewById(R.id.resultsName);
            extra = view.findViewById(R.id.resultsBonus);
            votePoints = new TextView[profiles.size()];

            // Add vote points to layout
            LinearLayout layout = view.findViewById(R.id.resultItemLayout);
            for (int i = 0; i < profiles.size(); i++) {
                // Use "layout" and "false" as parameters to get the width and height from result_voter_points
                TextView vote = (TextView) layoutInflater.inflate(R.layout.result_voter_points, layout, false);
                layout.addView(vote);
                votePoints[i] = vote;
            }
        }
    }
}
0 голосов
/ 04 мая 2020

Мне наконец удалось создать это, так что я решил поделиться этим здесь. Я использовал RecyclerView для этого, но если кто-нибудь знает, как это сделать с ListView, я с радостью воспользуюсь этим. Возможно, возможно сделать то же самое с помощью держателей представления в ListView? Я опубликую свои результаты, если это сработает.

// Adapter for creating the RecyclerView
public class ResultsAdapter extends RecyclerView.Adapter<ResultsAdapter.MyViewHolder> {

    private Context context;
    private List<ListItem> itemsList;
    private ArrayList<Profile> profiles;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public View view;
        public TextView name, extra, votes;
        public TextView[] votePoints;

        public MyViewHolder(View view) {
            super(view);
            this.view = view;
            name = view.findViewById(R.id.resultsName);
            extra = view.findViewById(R.id.resultsBonus);
            votes = view.findViewById(R.id.resultsVotePoints);
            votePoints = new TextView[profiles.size()];
        }
    }


    public ResultsAdapter(Context context, List<ListItem> itemsList, ArrayList<Profile> profiles) {
        this.itemsList = itemsList;
        this.profiles = profiles;
        this.context = context;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.result_show_votes_item, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        ListItem item = itemsList.get(position);
        holder.name.setText(item.getName());
        holder.extra.setText(String.valueOf(item.getTotal()));
        holder.votes.setText(String.valueOf(item.getVotePoints()));

        // Add vote points to layout
        LinearLayout layout = holder.view.findViewById(R.id.resultItemLayout);
        LayoutInflater inflater = LayoutInflater.from(context);
        for (int i = 0; i < profiles.size(); i++) {
            ListItem voteItem = itemsList.get(position);
            Profile profile = profiles.get(i);
            int voteAmount = profile.votePointsOfItem(voteItem);

            // Use "layout" and "false" as parameters to get the width and height from result_voter_points
            TextView vote = (TextView) inflater.inflate(R.layout.result_voter_points, layout, false);
            vote.setText(voteAmount == 0 ? "" : String.valueOf(voteAmount));
            layout.addView(vote);

            holder.votePoints[i] = vote;
        }
    }

    @Override
    public int getItemCount() {
        return itemsList.size();
    }
}
// Add profile names to topics
LinearLayout topicLayout = findViewById(R.id.topicLayout);
for (Profile p : selectedProfiles) {
    TextView name = (TextView) getLayoutInflater().inflate(R.layout.result_voter_name, topicLayout, false);
    name.setText(p.getName());
    topicLayout.addView(name);
}

RecyclerView recyclerView = findViewById(R.id.recycler_view);

ResultsAdapter adapter = new ResultsAdapter(this, selectedList.getItems(), selectedProfiles);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...