Android动态标签式菜单和内容(ViewPager)

时间:2017-08-29 04:56:58

标签: android android-fragments android-fragmentactivity fragmentmanager

我是Android开发的新手,我想动态显示标签式菜单。我不知道有多少Menu会来自服务器以及它的名字是什么。我已经成功地设置了数字和菜单名称(进入viewpager),但是其中有一些必须加载到片段中的细节。我不太清楚如何添加每个片段的细节(相应的片段)。

P.S。我只使用一个片段用于多个选项卡式菜单,因为它具有相同的字段。

我的问题是我如何能够显示或设置文本的详细信息?

以下是下载项目的链接: https://drive.google.com/open?id=0B6oKk-d9o9H4Skdsamw1bTZfREU

以下是文件

MainActivity.java

       package lalit.com.dynamictabbedmenu;
       import android.app.ProgressDialog;
       import android.content.Intent;
       import android.os.AsyncTask;
       import android.support.v7.app.AppCompatActivity;
       import android.os.Bundle;
       import android.util.Log;
       import android.view.View;
       import android.widget.Button;

       import com.android.volley.Request;
       import com.android.volley.RequestQueue;
       import com.android.volley.Response;
       import com.android.volley.VolleyError;
       import com.android.volley.toolbox.JsonObjectRequest;
       import com.android.volley.toolbox.Volley;

       import org.json.JSONArray;
       import org.json.JSONException;
       import org.json.JSONObject;

       import java.util.ArrayList;

       import lalit.com.dynamictabbedmenu.Model.MenuModel;

       public class MainActivity extends AppCompatActivity {
    Button Menu;
    private ProgressDialog pd;
    JSONObject jsonObject;
    int NoOfMenu;
    String[] ID;
    String[] MenuName;
    String[] Header;
    String[] Description;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pd = new ProgressDialog(this);

        Menu = (Button) findViewById(R.id.menu);
        Menu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                fetchAllMenu();
            }
        });
    }

    private void fetchAllMenu() {
        String URL_MENU = "http://altermirror.kuhipaat.in/ws/services/service_classes/service_classes_with_options.ws.php";

        RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, URL_MENU, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                new MenuListDetails(jsonObject).execute();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        queue.add(jsonObjectRequest);

    }

    private class MenuListDetails extends AsyncTask {
        MenuModel m;
        ArrayList<MenuModel> datalist;

        public MenuListDetails(JSONObject obj) {
            jsonObject = obj;
            datalist = new ArrayList<MenuModel>();
        }

      /*  @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd.setMessage("Please wait...");
            pd.setCancelable(false);
            pd.show();
        }*/

        @Override
        protected Object doInBackground(Object[] params) {
            try {
                JSONArray jsonArray = jsonObject.getJSONArray("results");
                NoOfMenu = jsonArray.length();
                ID = new String[NoOfMenu];
                MenuName = new String[NoOfMenu];
                Header = new String[NoOfMenu];
                Description = new String[NoOfMenu];
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject obj = jsonArray.getJSONObject(i);
                    m = new MenuModel();
                    ID[i] = (obj.getString("service_id"));
                    MenuName[i] = (obj.getString("service_name"));
                    Header[i] = (obj.getString("heading"));
                    Description[i] = (obj.getString("description"));
                    datalist.add(m);
                    Log.e("Menu Name:::" + i, MenuName[i]);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            Intent i = new Intent(MainActivity.this, TabbedMenuActivity.class);
            i.putExtra("NoOfMenu", NoOfMenu);
            for (int j = 0; j < NoOfMenu; j++) {
                i.putExtra("Menu" + j, MenuName[j]);
                i.putExtra("Header" + j, Header[j]);
                i.putExtra("Description" + j, Description[j]);
            }
            startActivity(i);
        }

    }
}

TabbedMenuActivity.java

    package lalit.com.dynamictabbedmenu;

    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.design.widget.TabLayout;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.support.v4.app.FragmentPagerAdapter;
    import android.support.v4.view.ViewPager;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.widget.TextView;

    import com.ToxicBakery.viewpager.transforms.AccordionTransformer;

    import java.util.ArrayList;
    import java.util.List;

    public class TabbedMenuActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    TextView tvBoldFont;
    private ProgressDialog pd;
    int NoOfMenu;
    String[] HeaderName;
    String[] DescriptionName;
    String[] MenuName;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabbedmenu);

        Bundle b = new Bundle();
        b = getIntent().getExtras();
        NoOfMenu = b.getInt("NoOfMenu");
        MenuName = new String[NoOfMenu];
        HeaderName = new String[NoOfMenu];
        DescriptionName = new String[NoOfMenu];
        for (int i = 0; i < NoOfMenu; i++) {
            MenuName[i] = b.getString("Menu" + i);
            HeaderName[i] = b.getString("Header" + i);
            DescriptionName[i] = b.getString("Description" + i);
        }

        pd = new ProgressDialog(this);

        String BoldFont = "Services";

        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.back_toolbar);

        tvBoldFont = (TextView) findViewById(R.id.tvBoldFont);
        tvBoldFont.setText(BoldFont);


        viewPager = (ViewPager) findViewById(R.id.container);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }


    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

        for (int i = 0; i < NoOfMenu; i++) {
            BlankFragment promiseCentralFragment = new BlankFragment();
            adapter.addFragment(promiseCentralFragment, MenuName[i]);
        }
        viewPager.setAdapter(adapter);
        viewPager.setPageTransformer(true, new AccordionTransformer());
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

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

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

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);

        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

}

BlankFragment.java

    package lalit.com.dynamictabbedmenu;


    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;

    public class BlankFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_blank, container, false);
    }

}

MenuModel.java

    package lalit.com.dynamictabbedmenu.Model;

    import java.io.Serializable;
    public class MenuModel implements Serializable {

    String service_id = "";
    String service_name = "";
    String heading = "";
    String description = "";

    public String getService_id() {
        return service_id;
    }

    public void setService_id(String service_id) {
        this.service_id = service_id;
    }

    public String getService_name() {
        return service_name;
    }

    public void setService_name(String service_name) {
        this.service_name = service_name;
    }

    public String getHeading() {
        return heading;
    }

    public void setHeading(String heading) {
        this.heading = heading;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

MenuListAdapter.java

    package lalit.com.dynamictabbedmenu.Adapter;

    import android.content.Context;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import java.util.List;

    import lalit.com.dynamictabbedmenu.Model.MenuModel;
    import lalit.com.dynamictabbedmenu.R;

    public class MenuListAdapter extends BaseAdapter {

    private Context activity;
    TextView serviceName, serviceHeading, serviceDescription;
    private LayoutInflater inflater;
    private List<MenuModel> model;

    public MenuListAdapter(Context activity, List<MenuModel> model) {
        this.activity = activity;
        this.model = model;
    }

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

    @Override
    public Object getItem(int position) {
        return model.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (inflater == null)
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.fragment_blank, null);
        }
        serviceName = (TextView) convertView.findViewById(R.id.service_name);
        serviceDescription = (TextView) convertView.findViewById(R.id.service_description);
        serviceHeading = (TextView) convertView.findViewById(R.id.service_heading);
        MenuModel menuModel = model.get(position);

        serviceName.setText(menuModel.getService_name());
        serviceHeading.setText(menuModel.getHeading());
        serviceDescription.setText(menuModel.getDescription());

        return convertView;
    }
}

以下是XML文件:

activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
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"
tools:context="lalit.com.dynamictabbedmenu.MainActivity">

        <Button
            android:id="@+id/menu"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Click for Menu"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

activity_tabbedmenu.xml

<?xml version="1.0" encoding="utf-8"?>
<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:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lalit.com.dynamictabbedmenu.TabbedMenuActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="center"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="#610505"
        app:tabTextColor="#FFF" />

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

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

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

back_toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="45dp"
android:background="@color/colorPrimary"
android:orientation="horizontal"
android:weightSum="6">

<LinearLayout
    android:id="@+id/llBackButton"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:padding="4dp"
    android:gravity="center_vertical">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/back" />
</LinearLayout>

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="4"
    android:gravity="center">

    <TextView
        android:id="@+id/tvBoldFont"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp" />
</LinearLayout>
</LinearLayout>

fragment_blank.xml

<FrameLayout 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"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="8dp">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="16dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/service_image"
                android:layout_width="match_parent"
                android:layout_height="218dp"
                android:foreground="@drawable/gradient"
                android:scaleType="centerCrop"
                app:srcCompat="@drawable/sample_service" />

            <TextView
                android:id="@+id/service_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="-40dp"
                android:text="Face Up"
                android:textColor="#FFF"
                android:textSize="18dp"
                android:textStyle="bold" />
        </LinearLayout>

        <TextView
            android:id="@+id/service_heading"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="Heading"
            android:textColor="#000" />

        <TextView
            android:id="@+id/service_description"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="10dp"
            android:text="descriptions here" />

    </LinearLayout>
</ScrollView>

</FrameLayout>

下图显示了带有内容的选项卡式菜单,但每个选项卡都有一些虚拟数据。 enter image description here

请帮我设置每个片段的内容。 提前谢谢。

0 个答案:

没有答案