Android:如何从另一个xml获取id

时间:2018-02-26 14:00:20

标签: android android-viewpager slide findviewbyid android-pageradapter

我有两个活动,MainActivity,SlideAdapter。 activity_main.xml中的一个ViewPager:

<android.support.v4.view.ViewPager
    android:id="@+id/option_view"
    android:layout_width="150dp"
    android:layout_height="150dp"
    .../>

option_slide.xml:

<ImageView
    android:id="@+id/chest"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:adjustViewBounds="true"
    android:src="@drawable/chest_lock"
    android:onClick="openChest"
    ... />

<ImageView
    android:id="@+id/circle"
    android:layout_width="30dp"
    android:layout_height="30dp"
    .../>

<TextView
    android:id="@+id/chest_number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/chest_number" />

<!-- Gallery -->
<ImageView
    android:visibility="gone"
    android:id="@+id/gallery"
    android:onClick="openGallery"
    ... />

SlideAdapter.class:

@Override
public Object instantiateItem(ViewGroup container, int position) {
    inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.option_slide,container,  false);


     imgView =  view.findViewById(R.id.chest);
     circle = view.findViewById(R.id.circle);
     chestNumber = view.findViewById(R.id.chest_number);


     imgView2 = view.findViewById(R.id.gallery);

    if (position==0) {
        imgView2.setVisibility(View.GONE);

        circle.setVisibility(View.VISIBLE);
        chestNumber.setVisibility(View.VISIBLE);
        imgView.setVisibility(View.VISIBLE);
    } else {
        imgView.setVisibility(View.GONE);
        circle.setVisibility(View.GONE);
        chestNumber.setVisibility(View.GONE);

        imgView2.setVisibility(View.VISIBLE);
    }
    container.addView(view);
    return view;
}

MainActivity.class:

viewPager = findViewById(R.id.option_view);
myAdapter = new SlideAdapter(this);
viewPager.setAdapter(myAdapter);

chest = findViewById(R.id.chest); //wrong
chestNumber = findViewById(R.id.chest_number); //wrong

胸部和numberText将返回null,并且应用程序崩溃... 我想知道如何从另一个布局获取id,我尝试了viewPager.findViewById,但没有工作。

0 个答案:

没有答案