通过Adapter动态添加TextView

通过Adapter根据类对象的里的数组属性的长度为LinearLayout动态加载TextView,使用BaseAdapter


基本功能:右侧显示Name,左侧排列显示value[]

item_list_view.xml:
    
    
    

    

创建一个SerialClass:我想实现左侧显示key,右侧对应多个values的情况,但不知道其他有什么合适的工具,查了下List、Map都不行,也可能可以用但我不知道(如果有知道的老师,望告知,谢谢)。
类包含两个变量:一个String name,另一个是数组String[] snValue
下面是代码:

public class SerialClass {
    private String name;
    private String[] snValue;

    public SerialClass(){};

    public SerialClass(String _name, String[] _snValue) {
        this.name = _name;
        this.snValue = _snValue;
    }
    public String getName() {
        return name;
    }
    public String[] getSnValue() {
        return snValue;
    }
    public void setName(String _name) {
        this.name = _name;
    }
    public void setSnValue(String[] _snValue) {
        this.snValue = _snValue;
    }
}

MyAdapter:为LinearLayout动态添加TextView

public class MyAdapter extends BaseAdapter {
    private SerialClass[] data;
    private Context context;
    private static final String ACTIVITY_TAG = "MyAdapter";
    public MyAdapter(Context _context,SerialClass[] _data) {
        this.context = _context;
        this.data = _data;
    }
    @Override
    public int getCount() {
        return data.length;
    }
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_list_view,null);
        TextView nameView = (TextView) view.findViewById(R.id.name_textView);
        nameView.setText(data[position].getName());
        LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.textLinearLayout);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
        for(int i=0;i

MainActivity:

public class MainActivity extends AppCompatActivity {

    private Context context;
    private SerialClass[] snData = new SerialClass[3];
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = MainActivity.this;
        String[] str01 = {"0f:12:22:a1:ee"};
        String[] str02 = {"test01","test02","test03"};
        String[] str03 = {"str2","str1"};
        for(int i=0;i

activity_main:

 
  
通过Adapter动态添加TextView_第1张图片
微信图片_20170802115316.png

你可能感兴趣的:(通过Adapter动态添加TextView)