Android,需要访问使用addView()动态创建的ImageView

时间:2015-07-07 22:35:36

标签: android

这是我想要做的 -

Slider with Title

虽然有许多部分涉及到这一点,但我认为如果我只能在下面的代码中引用动态创建的ImageView,我的问题就会消失。要完成图片中的内容,我一直在尝试使用Horizo​​ntalSrcollView。我动态创建ImageViews的代码 -

        for (int j = 1; j < cr_count + 1; j++) {
        LinearLayout l = (LinearLayout) findViewById(R.id.list);
        comp_hsv =
                (HorizontalScrollView) findViewById(R.id.scroller);
        ImageView i = new ImageView(getApplicationContext());
        i.setImageResource(android.R.drawable.btn_star_big_on);
        l.addView(i);
         comp_hsv.fullScroll(HorizontalScrollView.FOCUS_LEFT);
    }

my.XML -

            <HorizontalScrollView
            android:id="@+id/scroller"
            android:layout_width="200dp"
            android:layout_height="75dp"
            android:scrollbarSize="50dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true">

            <LinearLayout
                android:id="@+id/list"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="20dp"
                android:orientation="horizontal"
                android:layout_alignParentBottom="true"
                android:layout_centerHorizontal="true" />

        </HorizontalScrollView> 

我一直在互联网上跑步试图让这个工作,没有运气。任何建议/帮助都会很棒。

2 个答案:

答案 0 :(得分:0)

您可以在创建imageView.setId(urId)时使用ImageView。稍后使用imageView.getId()获取ID。 您可以循环浏览LinearLayout以检查ID

for (int i = 0; i < layout.getChildCount(); i++) {
        View v = layout.getChildAt(i);
        if (v instanceof ImageView) {
            //check id here
        } 
    }

答案 1 :(得分:0)

我更喜欢viewpager作为更好的解决方案。但是,如果您无法更改太多代码,您可以尝试使用这种廉价代码。

List<ImageView> refs = new ArrayList<ImageView>();

for (int j = 1; j < cr_count + 1; j++) {
    LinearLayout l = (LinearLayout) findViewById(R.id.list);
    comp_hsv = (HorizontalScrollView) findViewById(R.id.scroller);
    ImageView i = new ImageView(getApplicationContext());
    i.setImageResource(android.R.drawable.btn_star_big_on);
    l.addView(i);

--> refs.add(i);

    comp_hsv.fullScroll(HorizontalScrollView.FOCUS_LEFT);
}
相关问题