为什么从最后一个片段中的片段获取活动中的值项视图工作

时间:2017-12-28 08:23:00

标签: android listview spinner grouping

我正在开发Android应用程序。对不起,如果我的英语非常糟糕。我有一个问题,也许这里的朋友可以帮助解决我的问题。

我正在创建一个列表视图,可以通过布局和微调框选项卡进行分组。 enter image description here

在每个片段中,我创建了一个扩展到下面的一个布局:

fragment_patient_ranap.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container_pasien_register"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue_50"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:paddingTop="4dp">

<SearchView
    android:id="@+id/search_pasien_register"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:background="@drawable/search_view_border"
    android:iconifiedByDefault="false"
    android:queryHint="Cari Nama Pasien..."
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/search_pasien_register"
    android:gravity="center_horizontal"
    android:orientation="vertical">

    <!--Progress Bar-->
    <ProgressBar
        android:id="@+id/loading_pasien_registrasi"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/layout_two"
        android:visibility="gone" />

    <se.emilsjolander.stickylistheaders.StickyListHeadersListView
        android:id="@+id/listview_pasien_register"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_marginTop="4dp"
        android:divider="@color/blue_50"
        android:dividerHeight="2dp" />

    <TextView
        android:id="@+id/emptyData"
        android:layout_width="match_parent"
        android:layout_height="92dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="2dp"
        android:layout_marginTop="4dp"
        android:background="@color/icons"
        android:gravity="center"
        android:text="Tidak Ada Data!"
        android:textColor="@color/accent"
        android:textSize="12sp"
        android:textStyle="italic"
        android:visibility="gone" />

</LinearLayout>

在布局 Main 中,我定义了TabLayout和Spinner,如:

activity_patient_ranap.xml

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/holo_light"
tools:context="com.santosa.muhammadaa.mysantosa.PatientRanapActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar_pasien_ranap"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/primary"
        android:focusable="true"
        android:focusableInTouchMode="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/transparent">

            <TextView
                android:id="@+id/txt_title_label_pasien_ranap"
                style="@style/Base.TextAppearance.AppCompat.Title"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_toStartOf="@+id/spinner_ruangan"
                android:gravity="center_vertical"
                android:text="@string/title_pasien_ranap"
                android:textAllCaps="true"
                android:textColor="@android:color/white"
                android:textSize="16sp" />

            <Spinner
                android:id="@+id/spinner_ruangan"
                android:layout_width="@dimen/layout_normal"
                android:layout_height="match_parent"
                android:layout_marginBottom="@dimen/dimen_one"
                android:layout_toStartOf="@+id/view_img_refresh"
                android:gravity="center"
                android:textColor="@color/icons"
                android:theme="@android:style/Theme.Holo.Light.DarkActionBar" />


            <LinearLayout
                android:id="@+id/view_img_refresh"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_alignParentRight="true"
                android:layout_marginLeft="@dimen/dimen_two"
                android:layout_marginRight="@dimen/dimen_two"
                android:gravity="center_vertical"
                android:orientation="vertical">

                <ImageButton
                    android:id="@+id/img_refresh"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_gravity="center"
                    android:background="@android:color/transparent"
                    android:src="@drawable/ic_autorenew_white_24dp" />
            </LinearLayout>


        </RelativeLayout>

    </android.support.v7.widget.Toolbar>

</android.support.design.widget.AppBarLayout>

<android.support.design.widget.TabLayout
    android:id="@+id/tabs_menu"
    android:layout_width="match_parent"
    android:layout_height="44dp"
    android:background="@color/icons"
    android:paddingLeft="2dp"
    android:paddingRight="2dp"
    android:textAlignment="center"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    app:tabGravity="center"
    app:tabMode="scrollable"
    app:tabSelectedTextColor="@color/primary"
    app:tabTextColor="@color/secondary_text" />

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="44dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

但是当我从片段中获得值Spinner只是在最后一个片段中工作时,其他片段无效。

我的每个片段的代码TabLayout获取值Spinner,例如:

Spinner viewSpinner = getActivity().findViewById(R.id.spinner_ruangan);

我的代码流有问题吗?

请帮助我...我非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

Disclamer:这段代码没有经过测试,它的编写是为了让您了解我在谈论的内容,您可能需要更改许多行,因为它们可能会被破坏。 This是此处使用的事件总线。

在父活动中:

public class ParentActivity extends AppCompatActivity{ 
    //other activity's views (example: searchView, Button etc)
    private Spinner viewSpinner;
    private Viewpager viewPager;
    private ViewPager.OnPageChangeListener pageChangeListener;
    private WeakReference<BaseActivity> activityWeakReference = null; 


    @Override
    public void onCreate() {
     super.onCreate();
     setContentView(R.layout.your_layout);
     viewSpinner = (Spinner)findViewById(R.id.spinner_ruangan);
     viewPager = (ViewPager)findViewById(R.id.your_viewpager);
     pageChangeListener = definePageChangeListener();
     viewPager.setAdapter(new YourPagerAdapter(getSupportFragmentManager()));
     viewPager.addOnPageChangeListener(pageChangeListener); //add a onPageChangeListener to the viewPager

     //logic to define your fragments
    }

    @Override
    public void onStart() {
        super.onStart();

    }

    @Override
    public void onStop() {
     if(pageChangeListener != null && viewPager != null)
         viewPager.removeOnPageChangeListener(pageChangeListener); //remove the onPageChangeListener from the viewPager
     EventBus.getDefault().unregister(this);
     super.onStop();
    }


    public ViewPager.OnPageChangeListener definePageChangeListener(){
        return new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //you have the selected fragment's position here, just pass it to the right fragment using event bus
                switch(position){
                    case 0: 
                        EventBus.getDefault.post(new PageSelectedEvent(Fragment1.class.getSimpleName()));
                        break;
                    case 1: 
                        EventBus.getDefault.post(new PageSelectedEvent(Fragment2.class.getSimpleName()));
                        break;                  
                    case 2:                      
                        EventBus.getDefault.post(new PageSelectedEvent(Fragment3.class.getSimpleName()));
                        break;                   
                    case 3:                      
                        EventBus.getDefault.post(new PageSelectedEvent(Fragment4.class.getSimpleName()));
                        break;                   
                    default:                    
                        EventBus.getDefault.post(new PageSelectedEvent(Fragment1.class.getSimpleName()));
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        };
    }

    private class YourPagerAdapter extends FragmentPagerAdapter {
        ArrayList<CustomFragment> fragments = new ArrayList<CustomFragment>();
        public YourPagerAdapter(FragmentManager fm) {
            super(fm);
            //note that the fragments' constructor is up to you, you can have Fragment1(fragment.TAG, "id");
            fragments.add(new Fragment1()); //Fragment1 inherits CustomFragment that inherits Fragment class
            fragments.add(new Fragment2()); //Fragment2 inherits CustomFragment that inherits Fragment class
            fragments.add(new Fragment3()); //Fragment3 inherits CustomFragment that inherits Fragment class
            fragments.add(new Fragment4()); //Fragment4 inherits CustomFragment that inherits Fragment class
        }

        @Override
        public Fragment getItem(int pos) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }       
    }

    //this method will avoid memory leaks, yet it's result should always be checked to see if it is null
    public BaseActivity getActivityFromWeakReference(){
        activityWeakReference = activityWeakReference == null ?
                new WeakReference<BaseActivity>((BaseActivity)getActivity()) :
                activityWeakReference;
        return activityWeakReference.get();
    }

    public Spinner getViewSpinner(){
        if(viewSpinner == null)
            viewSpinner = (Spinner)findViewById(R.id.spinner_ruangan);
        return viewSpinner;
    }
}

事件类:

public class PageSelectedEvent{
    private String fragmentName = "";

    public PageSelectedEvent(String fragmentName){
        if(fragmentName == null || fragmentName.isEmpty()) // remove this line and the following line at production
            throw new NullPointerException("The fragmentName is null or empty. I shouldn't be the case.");

        this.fragmentName = fragmentName;
    }

    public String getFragmentName(){
        return fragmentName;
    }
}

CustomFragment

//in CustomFragment (that will be inherited by each of the 4 fragments)
protected Spinner viewSpinner = null;

public void onResume(){
    super.onResume();
    EventBus.getDefault().register(this);
}

public void onPause(){
    EventBus.getDefault().unregister(this);
    super.onPause();
}

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(NothingEvent event) {
    //EventBus will throw an exception if there is no subscriber.
    //So NothingEvent will avoid that exception.
}

private class NothingEvent{}

现在,在从CustomFragment继承的每个片段中,添加以下内容:

//now in each of the 4 fragments paste this code
@Subscribe(threadMode = ThreadMode.MAIN)  
public void onPageSelectedEvent(PageSelectedEvent event) {
    if(event.getFragmentName().equals(this.getSimpleName())){
        ParentActivity parentActivityReference = ((ParentActivity)getActivity()).getActivityFromWeakReference();
        viewSpinner = parentActivityReference.getViewSpinner(); //here you are assigning the parent's spinner's reference so that the currently displayed fragment has a reference to the activity's
    }
}