2017-06-02 58 views
0

我创建了一个具有线性布局的自定义适配器,并且我正在尝试向其动态添加一些图像。除最后一张外,所有图像都成功插入。Android:向LinearLayout添加多个图像时,最后一个图像不出现

编辑︰最后一个图像被添加到LinearLayout但它不会出于某种原因!

public View getView(int position, View convertView, ViewGroup parent) 
{ 
    LayoutInflater myCustomInflater = LayoutInflater.from(getContext()); 
    View customView = myCustomInflater.inflate(R.layout.custom_row, parent, false); 

    LinearLayout rowWordLayout =(LinearLayout) customView.findViewById(R.id.rowWordID); 

    String singleWord = getItem(position); 
    String[] characters = singleWord.split("-"); 

    for(int i=0; i<characters.length; i++){ 
     String symbol = characters[i]; 

     ImageView image = new ImageView(getApplicationContext()); 
     image.setImageResource(getResources().getIdentifier(symbol, "drawable", getPackageName())); 

     image.setLayoutParams(new android.view.ViewGroup.LayoutParams(80,60)); 
     image.setMaxHeight(20); 
     image.setMaxWidth(20); 
     image.setClickable(false); 

     rowWordLayout.addView(image); 
    } 
} 

回答

0

我想你应该在你的布局PARAM精确一weigth:

public View getView(int position, View convertView, ViewGroup parent) 
{ 
    LayoutInflater myCustomInflater = LayoutInflater.from(getContext()); 
    View customView = myCustomInflater.inflate(R.layout.custom_row, parent, false); 

    LinearLayout rowWordLayout =(LinearLayout) customView.findViewById(R.id.rowWordID); 

    String singleWord = getItem(position); 
    String[] characters = singleWord.split("-"); 

    for(int i=0; i<characters.length; i++){ 
     String symbol = characters[i]; 

     ImageView image = new ImageView(getApplicationContext()); 
     image.setImageResource(getResources().getIdentifier(symbol, "drawable", getPackageName())); 

     LayoutParams params = new LinearLayout.LayoutParams(0, 60, 1f); // Maybe LinearLayout.LayoutParams.WRAP_CONTENT it's more relevant than 60 
     image.setLayoutParams(params); 

     image.setMaxHeight(20); 
     image.setMaxWidth(20); 
     image.setClickable(false); 

     rowWordLayout.addView(image); 
    } 
} 

希望这有助于。

+0

我试了60和wrap_content,但它没有工作:( –

+0

我有另一个问题。这是我的错误。谢谢 –

1

试试这个...

的for(int i = 0;我< = characters.length;我++)

+0

我得到索引越界异常。其实我试图插入循环后的最后一个图像和我得到一个错误,说该图像已经有一个父母,这意味着它被插入,但它怎么不可见! –

0

我的坏。我对最后一个字符有问题,找不到相应的图像。

相关问题