简体   繁体   中英

Coordinator layout for xml

I want to use snackbar for displaying a message in any part of the app. I mean when wifi is disabled, there should be a snackbar saying wifi disabled. This is determined in any part of the app (any fragment or any activity). Currently I am determing this in subfragment where all fragments extend subfragment and also I use it in MainActivity . This works fine. The problem is with coordinator layout for snackbar . How can I give this coordinator layout in each xml? What is the best possible solution?

It seems as though you want to use a parent layout structure for all of your other layouts. Let's say our parent layout file is called structure.xml and it looks something like this:

<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

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

Then, whenever you create an activity you can inflate your usual layout, say activity_main.xml , like this:

 @Override
 protected void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);

     setContentView(R.layout.structure);
     LayoutInflater.from(this).inflate(R.layout.activity_main, (FrameLayout) findViewById(R.id.container), false);
 }

And whenever you create a fragment with your usual layout, say frag_main.xml , you can do it like this:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved) {
    View view = inflater.inflate(R.layout.structure, group, false);
    inflater.inflate(R.layout.frag_main, (FrameLayout) view.findViewById(R.id.container), false);

    return view;
}

Since you've already got a parent class for your fragments/activities you should be able to easily create some helper methods for all of your subclasses to use.

Hope this helps.

i think the common way is to Traversal the root view and find the child who is instance of CoordinatorLayout, the code segment may be as blow :

public View getCoordinateLayout(Activity activity) {
    ViewGroup vg = (ViewGroup) activity.findViewById(android.R.id.content);
    ViewGroup root = (ViewGroup) vg.getChildAt(0);
    int childCount = root.getChildCount();
    for(int i=0;i<childCount;i++){
        View view = root.getChildAt(i);
        if(view instanceof CoordinatorLayout){
            return view;
        }
    }
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM