2014-02-27 61 views
0

我有一个listview自定义适配器,这里是getView方法;动态创建ImageViews不显示图像

 @Override 
     public View getView(int i, View view, ViewGroup viewGroup) { 
      LayoutInflater inflater = (LayoutInflater) JourneyPlannerActivity.this 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

      View rowView = inflater.inflate(R.layout.journey_planner_route_detail, viewGroup, false); 
      LinearLayout layout = (LinearLayout) rowView.findViewById(R.id.journey_planner_detail_detail_main_id); 

      JourneyPlannerRoute r = m_Routes.get(i); 
      String directions = ""; 
      for(int j=0 ; j < r.getRoutes().size() ; j++){ 
       ImageView image = new ImageView(JourneyPlannerActivity.this); 
       String transportMethod = r.getRoutes().get(j).getMeansOfTransport(); 
       if(transportMethod.equals("Train")) 
        image.setImageResource(R.drawable.network_rail_logo); 
       else if(transportMethod.equals("Subway")) 
        image.setBackgroundResource(R.drawable.roundel_tube); 
       else if(transportMethod.equals("Bus")) 
        image.setBackgroundResource(R.drawable.bus); 
       else if(transportMethod.equals("Walk")) 
        image.setBackgroundResource(R.drawable.walking); 
       image.setVisibility(View.VISIBLE); 
       layout.addView(image); 
       //directions += r.getRoutes().get(j).getMeansOfTransport()+","; 
      } 
      directions += " "+r.getDuration(); 

      TextView tv = (TextView) rowView.findViewById(R.id.journey_planner_detail_main_text_view); 
      tv.setText(directions); 

      return rowView; 

经过调试后,似乎图像被添加到布局,但他们只是没有出现在屏幕上;

enter image description here

我有一种感觉,这是由于不拾取正确的布局,但它好像是?

这是行的xml文件;

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <LinearLayout 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:id="@+id/journey_planner_detail_detail_main_id"> 

     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:background="@drawable/bus_small"/> 

     <TextView 
      android:id="@+id/journey_planner_detail_main_text_view" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" /> 

    </LinearLayout> 

</LinearLayout> 
+0

你可以添加项目布局的XML代码? – Tautvydas

+0

对不起,知道我错过了一些东西。 – r0bb077

回答

2

而不是创建新的图像视图只需调用rowView.findViewById(R.id.image_id);(你必须添加id到XML)。

实际的错误是TextView。它被设置为fill_parent,导致新添加的ImageView出现在可见屏幕的右侧。您可以通过将TextView宽度更改为wrap_content来更改此设置。但是,使用在xml布局中定义的ImageView更好。

+0

真棒,我甚至没有考虑过我的布局,傻人!再次感谢,我会尽我所能接受。 – r0bb077