动态创建ImageView不显示图像

时间:2014-02-27 18:17:46

标签: android imageview

我有listview的自定义适配器,这是getView方法;

        @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>

1 个答案:

答案 0 :(得分:2)

不要创建新的图片视图,只需调用rowView.findViewById(R.id.image_id);(您必须将id添加到xml中)。

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