当前位置: 首页 > 知识库问答 >
问题:

选项卡内的网格布局

苏野
2023-03-14

我是Android新手,因此面临这样的问题。

fragment_main:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.snbgearassistant.MainActivity$PlaceholderFragment" >


<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

</RelativeLayout>

所以我需要这些标签有不同内容的网格布局。

共有2个答案

令狐翰
2023-03-14
Answer Given By rogcg is very good and nice. But the Images for each fragment is same. I like to add some codes in the mainactivity which has viewpager.I think we can use fragment instead of activity, Here is the code.The same code as the Main Activity given by rogcg. Add these codes too.
In Layout for mainfragment add ActionBarlayout,toolbar and slidingtablayout
In Mainfragment,add 
  private List<Fragment> mFragments = new Vector<Fragment>();
 in oncreate(), create three fragments , 
    mFragments.add(new HomeFragment());
    mFragments.add(new Title1());
    mFragments.add(new Title2());
    mFragments.add(new Title3());
  in onCreateView(),add 
      mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
    mViewPager.setAdapter(mSectionsPagerAdapter);
    tabLayout = (SlidingTabLayout) v.findViewById(R.id.tabanim_tabs);
    tabLayout.setViewPager(mViewPager);
  in SectionPageAdapter class,add
    @Override
    public Fragment getItem(int position) {

        return mFragments.get(position+1);
    }

    @Override
    public int getCount() {

        return 3;

    }

    @Override
    public CharSequence getPageTitle(int position) {
      Locale l = Locale.getDefault();
        switch (position)
        {
            case 0:
                return getString(R.string.English).toUpperCase(l);
            case 1:
                return getString(R.string.Tamil).toUpperCase(l);
            case 2:
                return getString(R.string.Hindi).toUpperCase(l);
        }
        return null;

    }
 Now add any view in Title1() fragment as you usage and add any things in it I think this message was useful. please vote for me. Thank you.
韩梓
2023-03-14

必须在ViewPager中使用GridView。因此,在您的< code>MainActivity中,您将有这样的布局。

这是主布局。所有东西都将生活在其中,包括你的片段和标签。

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.myapp.gridview.MainActivity" />
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener 
{

    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Here we load the xml layout we created above
        setContentView(R.layout.activity_main);

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() 
        {
            @Override
            public void onPageSelected(int position) 
            {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) 
        {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }


    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
    {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
    {

    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) 
    {

    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter
    {

        public SectionsPagerAdapter(FragmentManager fm) 
        {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) 
        {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return new PlaceholderFragment();
        }

        @Override
        public int getCount() 
        {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) 
        {
            Locale l = Locale.getDefault();
            switch (position) 
            {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }
}

不要忘记为这些R.string.title_section1创建字符串,在代码上使用... 字符串,否则您将遇到错误。

现在我们必须为片段(将在选项卡内显示的页面)创建布局,并且它必须包含GridView

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2" />
</FrameLayout>

现在,让我们定义一个片段类,它将负责扩展这个布局和处理视图。

/**
 * A placeholder fragment containing a the gridview
 */
public class PlaceholderFragment extends Fragment 
{
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        // Here we inflate the layout we created above
        GridView gridView = (GridView) rootView.findViewById(R.id.gridview);
        gridView.setAdapter(new MyAdapter(MainActivity.this.getApplicationContext()));

        return rootView;
    }
}

现在我们必须创建一个适配器类来处理<code>GridView

正如您在这里看到的,我们将一些项添加到GridView中,方法是将它们添加到适配器类末尾定义的Item类型的ArrayList

private class MyAdapter extends BaseAdapter
{
        private List<Item> items = new ArrayList<Item>();
        private LayoutInflater inflater;

        public MyAdapter(Context context)
        {
            inflater = LayoutInflater.from(context);

            items.add(new Item("Image 1", Color.GREEN));
            items.add(new Item("Image 2", Color.RED));
            items.add(new Item("Image 3", Color.BLUE));
            items.add(new Item("Image 4", Color.GRAY));
            items.add(new Item("Image 5", Color.YELLOW));
        }

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

        @Override
        public Object getItem(int i)
        {
            return items.get(i);
        }

        @Override
        public long getItemId(int i)
        {
            return items.get(i).colorId;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup)
        {
            View v = view;
            ImageView picture;
            TextView name;

            if(v == null)
            {
                v = inflater.inflate(R.layout.gridview_item, viewGroup, false);
                v.setTag(R.id.picture, v.findViewById(R.id.picture));
                v.setTag(R.id.text, v.findViewById(R.id.text));
            }

            picture = (ImageView)v.getTag(R.id.picture);
            name = (TextView)v.getTag(R.id.text);

            Item item = (Item)getItem(i);

            picture.setBackgroundColor(item.colorId);
            name.setText(item.name);

            return v;
        }

        private class Item
        {
            final String name;
            final int colorId;

            Item(String name, int drawableId)
            {
                this.name = name;
                this.colorId = drawableId;
            }
        }
    }

现在,为了使<code>GridView

为什么需要这样做?根据@kcoppock的回答:

基本上,在Android的ImageView类中,除非您硬编码宽度和高度,否则无法简单地指定“嘿,为此视图保留正方形纵横比(宽度/高度)”。您可以在适配器的 getView 中对布局参数进行一些手动调整,但坦率地说,让 ImageView 处理所有测量值要简单得多,只需覆盖结果即可显示“无论宽度如何,都要使我的身高保持不变”。你永远不必考虑它,它总是方形的,它只是按预期工作。基本上,这是保持视场的最简单方法。

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class SquareImageView extends ImageView
{
    public SquareImageView(Context context)
    {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

现在,我们必须为< code>GridView项定义XML布局。

如您所见,在这里我们向布局中添加两个项目。一个是方形图像视图类型(我们上面创建的类)的元素和文本视图,它是每个图像的标签。

<?xml version="1.0" encoding="utf-8"?>

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.myapp.gridview.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"
        />
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"
        />
</FrameLayout>

在这里,我测试了代码,这是最终结果。当然,你可以改变图片的颜色,但这是你应该遵循的方法。

注: 若要为 GridView 项设置图像而不是颜色,请在 MyAdapter 类的 getView() 方法中使用 setImageResource(int) 而不是 setBackgroundColor(int)

 类似资料:
  • 我对tabView有问题。第一个选项卡应始终显示相同的内容(称为搜索模板,用#{not curSearch.isClosable()}标识)。所有其他选项卡都是搜索实例(用#{curSearch.isClosable()}标识) 代码如下: 不幸的是,在第一个选项卡上有一些被称为curSearch对象的方法,这些方法仅在第二个选项卡和后面的选项卡上使用。如果我不使用ui:insert,它不会改变任

  • java-jar selenium-server-standalone-2.16.0.jar-role webdriver-hub http://a.b.c.d:4444/grid/register ?

  • 我已经搜索了很多关于如何使用SlidengTablayout在片段之间进行通信的内容,但还没有找到一个好的答案。我知道使用ActionBar,但我想要的是androidLollipop使用SlidingTabLayout的新方式。我试过了-

  • 我想创建一个应用程序,使用带有滑动视图的选项卡布局(类似于这样): 问题来了:我在网上到处找一个可以解释如何做这种事情的指南,但我所做的一切都对我不起作用。我在某个地方读到标签布局与Lollipop是不推荐的,所以我试图找到一个替代的方法来做我想做的事情,但什么也没有。我试图创建的每个选项卡布局应用程序在测试时都以崩溃告终,我认为这是由于的某些原因,总是因为选项卡在Lollipop中是不推荐的。我

  • 页边距在它们之间的选项卡和选定的选项卡上有一个勾号

  • 问题内容: 我在StackOverflow中发现了大量这些消息。像其他许多人一样,切换标签时,标签内容重叠也存在相同的问题。我发现的任何建议都无法解决我的问题。 当我的应用启动时,它会正确显示第一个选项卡的内容。当我单击另一个选项卡时,旧内容保留在屏幕上,另一个选项卡的内容也添加在屏幕上。第二次切换选项卡时,所有内容均消失。切换标签不再有用。 我在这里关注了Google的Developer文档。