如何在android中动态设置ListView中n个TextView的TextView宽度?

时间:2016-01-19 12:53:18

标签: android listview textview

我想创建一个Listview水平地保存1到'n'个TextView数据,这个Textview数据和宽度大小将来自DB? 我不知道如何用持有人动态设置TextView的宽度?谢谢你提前。

@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    ViewHolder holder  = new ViewHolder();

    if (view == null) {
        view = View.inflate(cntxts, R.layout.list_header_col, null);
        String [] ColNmae= (String[]) objects.get(0);

        int Width= Integer.parseInt(ColNmae[2].toString());
        LinearLayout layout=new LinearLayout(cntxts);
       // layout.setLayoutParams(new LinearLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
        TextView Textview = new TextView(cntxts);
        HorizontalScrollView hr = new HorizontalScrollView(cntxts);
        for(int i=0;i<objects.size();i++) {
            holder.Textview=new TextView(cntxts);
            layout.setLayoutParams(new RelativeLayout.LayoutParams(Width,80));
            layout.addView(holder.Textview);
        }
        hr.addView(layout);
        view = hr;
        view.setTag(holder);
    } else {
        holder = (ViewHolder) view.getTag();
    }
    notifyDataSetChanged();
    final String[] objMain = (String[]) getItem(position);
        holder.Textview.setText(objMain[0]);
    return view;
}

3 个答案:

答案 0 :(得分:0)

您的数据需要来自某个地方。要实现 Spinner ,您可以选择以下选项:

  • 将值放在布局文件中
  • 输入代码
    • 建立自己的价值观
    • 从数据库中检索

答案 1 :(得分:0)

试试这个,

 yourholder.textView.getLayoutParams().width = dynamic width value;

答案 2 :(得分:0)

Thanks for your help I have got the solution.

 try {
                LayoutInflater mInflater = (LayoutInflater)
                        cntxts.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                view = mInflater.inflate(R.layout.list_header_col, null);

                holder.layoutmain = (LinearLayout) view.findViewById(R.id.lyt_header);

                view.setTag(holder);

                String[] ColNmae = (String[]) objects.get(0);

                int Width = Integer.parseInt(ColNmae[2].toString());
                if (holder.layoutmain != null && holder.layoutmain.getChildCount() > 0)
                    holder.layoutmain.removeAllViews();

                for (int i = 0; i < objects.size(); i++) {
                    final String[] objMain = (String[]) getItem(i);
                    TextView textView = new TextView(cntxts);
                    textView.setText(objMain[0]);
                    holder.layoutmain.addView(textView);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }