简体   繁体   English

Android ViewPager - 如何向页面添加按钮?

[英]Android ViewPager - How to add buttons to the pages?

I am following this link to do a ViewPager http://blog.stylingandroid.com/archives/537 I managed to get the various pages out. 我正在关注这个链接来做一个ViewPager http://blog.stylingandroid.com/archives/537我设法得到了各种各样的页面。 But how do I populate or fill these pages with buttons? 但是如何使用按钮填充或填充这些页面?

instantiateItem() instantiateItem()

This creates the view for a given position. 这将创建给定位置的视图。 For a real application we would use a Fragment here, or inflate a layout, but to keep the example simple we create a TextView, set the text to the correct value from our titles array, and add it to the ViewPager 对于一个真正的应用程序,我们将在这里使用Fragment,或者扩展布局,但为了使示例简单,我们创建一个TextView,将文本设置为我们的titles数组中的正确值,并将其添加到ViewPager

I want to have different button functions on different pages. 我想在不同的页面上有不同的按钮功能。 How do I go about doing this? 我该怎么做呢? By using different layout? 通过使用不同的布局? How do I put the layout within the page (is this what you call inflat)? 如何将布局放在页面中(这就是你所说的inflat)?

EDIT: I have the main.xml which consists of the ViewPager 编辑:我有一个由ViewPager组成的main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:weightSum="1">

    <com.viewpagerindicator.TitlePageIndicator
        android:id="@+id/indicator"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1" />        
</LinearLayout>

I have several other xml which consists of buttons which I want to inflate it into the different pages of the ViewPage. 我有几个其他xml,它包含按钮,我想将它膨胀到ViewPage的不同页面。 Example of an xml. 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="match_parent"
    android:orientation="vertical" >

    <Button android:layout_width="match_parent" android:text="Button 1" android:onClick="onClick" android:id="@+id/button1" android:layout_height="100dp"></Button>
    <Button android:text="Button 2" android:onClick="onClick" android:id="@+id/button2" android:layout_width="match_parent" android:layout_height="100dp"></Button>
    <Button android:text="Button 3" android:onClick="onClick" android:id="@+id/button3" android:layout_width="match_parent" android:layout_height="100dp"></Button>
    <Button android:text="Button 4" android:onClick="onClick" android:id="@+id/button4" android:layout_width="match_parent" android:layout_height="100dp"></Button>
    <Button android:text="Button 5" android:onClick="onClick" android:id="@+id/button5" android:layout_height="match_parent" android:layout_width="match_parent"></Button>

</LinearLayout>

In the ViewPagerAdapter.java, I managed to inflate the various XML into the pages. 在ViewPagerAdapter.java中,我设法将各种XML扩展到页面中。

@Override
public Object instantiateItem( View pager, int position )
{
    //Inflate the correct layout
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    //layouts[] is an int[] that points to resources such as R.layout.start_page
    View inflatedView = layoutInflater.inflate(layouts[position], null);

    ((ViewPager)pager).addView(inflatedView,0);

    return inflatedView;

}

And this needs to be changed to prevent error. 这需要改变以防止错误。

@Override
public void destroyItem( View pager, int position, Object view )
{
    ((ViewPager)pager).removeView( (View)view );
}

Now, I have multiple buttons on different pages. 现在,我在不同的页面上有多个按钮。 How do I programme the ONCLICK function of the different buttons on the different pages? 如何编程不同页面上不同按钮的ONCLICK功能? Can this work? 这可以吗?

public void onClick(View v) {
        switch (v.getId()) {
        case R.id.button1:
            // do something
            break;
        case R.id.button2:
            // do something
            break;
        case R.id.button3:
            // do something
            break;
        case R.id.button4:
            // do something
            break;
        case R.id.button5:
            // do something
            break;
        }
    }

Here is an example of inflating/programmatically adding views with buttons: 以下是使用按钮膨胀/以编程方式添加视图的示例:

@Override
//Instantiate items based on corresponding layout IDs that were passed in
public Object instantiateItem(View container, int position)
{
    //Inflate the correct layout
    LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    //layouts[] is an int[] that points to resources such as R.layout.start_page
    View inflatedView = layoutInflater.inflate(layouts[position], null);

    ((ViewPager)container).addView(inflatedView,0);

    //If you can't/don't want to have the above inflated layout include everything up front, you can add them now...
    LinearLayout ll = (LinearLayout)inflatedView.findViewById(R.id.linearLayout1);
    Button newButton = new Button(context);
    newButton.setText(R.string.button_text);
    ll.addView(newButton);

    return inflatedView;
}

I recently set up a system with a ViewPage r. 我最近建立了一个带有ViewPage r 的系统 I use actionbar tabs (with compatibility library), a TabAdapter and ViewPager. 我使用操作栏选项卡(带兼容性库),TabAdapter和ViewPager。 Each tab is its own fragment and added into the bar via the main activity. 每个选项卡都是自己的片段,并通过主要活动添加到栏中。 Here is some of the key code: 以下是一些关键代码:

public class Polling extends FragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
final ActionBar bar = getActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);

mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
}

And the adapter: 和适配器:

public static class TabsAdapter extends FragmentPagerAdapter
    implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
        private final Context mContext;
        private final ActionBar mActionBar;
        private final ViewPager mViewPager;
        private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

        static final class TabInfo {
            private final Class<?> clss;
            private final Bundle args;

            TabInfo(Class<?> _class, Bundle _args) {
                clss = _class;
                args = _args;
            }
        }

        public TabsAdapter(FragmentActivity activity, ViewPager pager) {
            super(activity.getSupportFragmentManager());
            mContext = activity;
            mActionBar = activity.getActionBar();
            mViewPager = pager;
            mViewPager.setAdapter(this);
            mViewPager.setOnPageChangeListener(this);
        }

        public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
            TabInfo info = new TabInfo(clss, args);
            tab.setTag(info);
            tab.setTabListener(this);
            mTabs.add(info);
            mActionBar.addTab(tab);
            notifyDataSetChanged();
        }


        public int getCount() {
            return mTabs.size();
        }

        public Fragment getItem(int position) {
            TabInfo info = mTabs.get(position);
            return Fragment.instantiate(mContext, info.clss.getName(), info.args);
        }


        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }


        public void onPageSelected(int position) {
            mActionBar.setSelectedNavigationItem(position);
        }


        public void onPageScrollStateChanged(int state) {
        }


        public void onTabSelected(Tab tab, FragmentTransaction ft) {
            mViewPager.setCurrentItem(tab.getPosition());
            Log.v(TAG, "clicked");
            Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                }
            }
        }

        public void onTabUnselected(Tab tab, FragmentTransaction ft) {}

        public void onTabReselected(Tab tab, FragmentTransaction ft) {}

        public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {}

        @Override
        public void onTabSelected(Tab tab, android.app.FragmentTransaction ft) {    
            Object tag = tab.getTag();
            for (int i=0; i<mTabs.size(); i++) {
                if (mTabs.get(i) == tag) {
                    mViewPager.setCurrentItem(i);
                }
            }
        }

        public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {}
    }

And here's a class that makes buttons and widgets on each tab: 这是一个在每个选项卡上创建按钮和小部件的类:

public class EconFragment extends SherlockFragment {

Polling activity;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    activity = (Polling)getActivity();

    View v = inflater.inflate(R.layout.categoryfragment, container, false);
    this.mainLayout = v;
    return v;
}

So long as you edit the XML file that is inflated in the above code (categoryfragment.xml), each tab will load whatever you want to put on the page (TextView, Button, etc). 只要您编辑上面代码中夸大的XML文件(categoryfragment.xml),每个选项卡都会加载您想要放在页面上的任何内容(TextView,Button等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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