android - 选项卡 fragment 内的 gridview

标签 android eclipse gridview android-fragments

我的项目需要帮助,我正在学习本教程,我发现创建一个带有抽屉导航和选项卡的应用程序,当您运行该应用程序时,它将如下所示:

enter image description here

我正尝试使用 GridView 更改选项卡 fragment 内的 View ,所以我需要帮助任何人都可以告诉我应该在哪里以及如何添加 GridView

所以这是我的主要 Activity java :

@SuppressWarnings("deprecation")
public class MenuUtama extends ActionBarActivity{

    Toolbar toolbar;
    private ViewPager mPager;
    private SlidingTabLayout mTabs;
    public DaftarMakanan foodList;
    GridView makananGrid;

    ViewPager viewPager;
    ActionBar actionBar;

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


        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);

        NavDrawerFragment drawerFragment = (NavDrawerFragment) getSupportFragmentManager()
                .findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);

        mPager = (ViewPager) findViewById(R.id.MyPager);
        mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

        mTabs = (SlidingTabLayout) findViewById(R.id.MyTabs);
        mTabs.setDistributeEvenly(true);
        mTabs.setCustomTabView(R.layout.custom_tab_view, R.id.tabsText);
        mTabs.setBackgroundColor(getResources().getColor(R.color.orange));
        mTabs.setSelectedIndicatorColors(getResources().getColor(R.color.brown));

        mTabs.setViewPager(mPager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_utama, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Toast.makeText(this, "This Is " + item.getTitle() + " Button",
                    Toast.LENGTH_SHORT).show();
            return true;
        }

        if (id == R.id.bill) {
            startActivity(new Intent(this, BillTagihanAnda.class));
        }

        if (id == R.id.pesanan) {
            startActivity(new Intent(this, DaftarPesananAnda.class));
        }

        if (id == R.id.callwaiter) {
            startActivity(new Intent(this, PanggilPelayan.class));
            finish();
        }
        return super.onOptionsItemSelected(item);
    }



    class MyPagerAdapter extends FragmentPagerAdapter {

        int icon[] = { R.drawable.ic_food, R.drawable.ic_drink, R.drawable.ic_desserts };
        String[] tabsText = getResources().getStringArray(R.array.tabs);


        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
            tabsText = getResources().getStringArray(R.array.tabs);

        }

        @Override
        public Fragment getItem(int position) {
            MyFragment myFragment = MyFragment.getInstance(position);
            return myFragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Drawable drawable = getResources().getDrawable(icon[position]);
            drawable.setBounds(0, 0, 40, 40);
            ImageSpan imageSpan = new ImageSpan(drawable);
            SpannableString spannableString = new SpannableString(" ");
            spannableString.setSpan(imageSpan, 0, spannableString.length(),
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

            return spannableString;
        }

        @Override
        public int getCount() {
            return 3;
        }

    }

    public static class MyFragment extends Fragment {
        private TextView textView;
        private GridView gridView;

        public static MyFragment getInstance(int position) {
            MyFragment myFragment = new MyFragment();
            Bundle args = new Bundle();
            args.putInt("position", position);
            myFragment.setArguments(args);
            return myFragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View layout = inflater.inflate(R.layout.my_fragment, container, false);
            textView = (TextView) layout.findViewById(R.id.position);
            gridView = (GridView) layout.findViewById(R.id.gridView);
            Bundle bundle = getArguments();
            if (bundle != null) {
                textView.setText("The Page Selected is " + bundle.getInt("position"));
            }

            return layout;
        }

    }

}

我的主要 Activity xml:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:yourapp="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="id.WKKR.ktcafe.MenuUtama" >

        <include
            android:id="@+id/app_bar"
            layout="@layout/app_bar" />

        <tabs.SlidingTabLayout
            android:id="@+id/MyTabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <android.support.v4.view.ViewPager
            android:id="@+id/MyPager"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
    </LinearLayout>

    <fragment
        android:id="@+id/fragment_navigation_drawer"
        android:name="id.WKKR.ktcafe.NavDrawerFragment"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        tools:layout="@layout/activity_nav_drawer_fragment"
        yourapp:layout="@layout/activity_nav_drawer_fragment" />

</android.support.v4.widget.DrawerLayout>

和我的 fragment xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/position"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:text="Page Number 1"
    android:textColor="@color/black"
    android:textSize="20sp" />

(已编辑) 所以我用 GridView 更改了 fragment xml,现在我应该在哪里放置 GridView 的适配器来显示数据,我应该创建新的适配器类还是只在里面添加适配器主要 Activity java类? :

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="150dp"
    android:numColumns="3"
    android:stretchMode="spacingWidthUniform" >

</GridView>

最佳答案

我终于明白了

所以我创建了一个新的适配器类来膨胀网格内容

所以这是我的网格适配器类,称为食物适配器:

package id.WKKR.ktcafe;

import java.util.ArrayList;

import android.content.Context;
import android.content.res.Resources;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class FoodAdapter extends BaseAdapter {

	ArrayList<Menus> list;
	Context context;

	FoodAdapter(Context context) {
		this.context = context;
		list = new ArrayList<Menus>();
		Resources res = context.getResources();
		String[] tempMenusNames = res.getStringArray(R.array.food);
		String[] tempMenusPrices = res.getStringArray(R.array.foodprices);
		int[] menusImages = { R.drawable.makanana, R.drawable.makananb,
				R.drawable.makananc, R.drawable.makanand, R.drawable.makanane,
				R.drawable.makananf };
		for (int i = 0; i < 6; i++) {
			Menus tempMenus = new Menus(menusImages[i], tempMenusNames[i],
					tempMenusPrices[i]);
			list.add(tempMenus);
		}

	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return list.size();
	}

	@Override
	public Object getItem(int i) {
		// TODO Auto-generated method stub
		return list.get(i);
	}

	@Override
	public long getItemId(int i) {
		// TODO Auto-generated method stub
		return i;
	}

	@Override
	public View getView(int i, View convertView, ViewGroup parent) {
		View row = convertView;
		ViewHolder holder = null;
		if (row == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(R.layout.single_item, parent, false);
			holder = new ViewHolder(row);
			row.setTag(holder);
		} else {
			holder = (ViewHolder) row.getTag();
		}

		Menus temp = list.get(i);
		holder.myMenus.setImageResource(temp.imageId);
		holder.myMenusText.setText(temp.menus);
		holder.MyMenusPrice.setText(temp.menusPrices);

		return row;
	}

	class ViewHolder {
		ImageView myMenus;
		TextView myMenusText;
		TextView MyMenusPrice;

		ViewHolder(View v) {
			myMenus = (ImageView) v.findViewById(R.id.imageView1);
			myMenusText = (TextView) v.findViewById(R.id.textView1);
			MyMenusPrice = (TextView) v.findViewById(R.id.textView2);
		}
	}

	class Menus {
		int imageId;
		String menus;
		String menusPrices;

		Menus(int imageId, String menus, String menusPrices) {
			this.imageId = imageId;
			this.menus = menus;
			this.menusPrices = menusPrices;
		}
	}

}

食物适配器内的 getView 方法将膨胀一个名为 single_item.xml 的 xml,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="15dp" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:src="@drawable/makanana" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="Rp. " />

</RelativeLayout>

然后在我的主要 Activity java 中,我在 my_fragment.xml 和适配器中获取我的 gridview 的引用,然后在 onCreateView 方法中设置适配器。

public static class MyFragment extends Fragment {
		private TextView textView;
  
        //add gridview and foodadapter in fragment
		private GridView gridView;
		private FoodAdapter foodAdapter;

		public static MyFragment getInstance(int position) {
			MyFragment myFragment = new MyFragment();
			Bundle args = new Bundle();
			args.putInt("position", position);
			myFragment.setArguments(args);
			return myFragment;
		}

		@Override
		public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
			View layout = inflater.inflate(R.layout.my_fragment, container, false);
            
            //and here i get the reference of gridview from my_fragment.xml and set the adapter
			gridView = (GridView) layout.findViewById(R.id.gridView);
			foodAdapter = new FoodAdapter(getActivity());
			gridView.setAdapter(foodAdapter);

			return layout;
		}

	}

当您运行该应用程序时,它将看起来像这样的图片:http://i61.tinypic.com/9sgsjs.jpg .

关于android - 选项卡 fragment 内的 gridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30054419/

相关文章:

java - 我的上一个 ImageView 图像按钮不起作用

android - 安装新软件时的Eclipse问题

android - 无法捕获 GridView 的 MotionEvent.ACTION_DOWN

Android:水平居中gridview

javascript - JS 到 Dart 转换

c# - ASP.NET - 扩展 gridview 以允许过滤、排序、分页等

android - 使用 Espresso 进行测试时,如何在 Android 上的 NavigationView 中单击菜单项?

java - 在 Android 中映射 XML 属性和代码方法

android - 内联显示 View ?

java - JRebel 远程服务器即服务