android - fragment 内的按钮

标签 android button fragment

我希望有人能帮我解决这个非常烦人的问题。我刚开始使用 fragment 。我花了两天时间试图让按钮在我的 fragment 中工作。我的应用程序是一个选项卡 Activity ,带有由 android studio 自动创建的滑动 fragment 。我可以通过滑动和使用选项卡来更改 fragment 。但是我无法让按钮响应。我的应用程序没有崩溃,我的 Log.e 没有在 Logcat 中注册。我从互联网上复制了很多例子,但似乎没有任何效果。

我已经尝试实现 View.OnClickListener 并且没有实现它,但没有任何效果。我将发布两个应该有效但无效的示例。

没有实现 View.OnClickListener 的 FRAGMENT

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
     View rootView = inflater.inflate(R.layout.fragment_summary_loggs, container, false);
     Button test = (Button) rootView.findViewById(R.id.testButton);
    test.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.e("DEBUGG", "BUTTON PRESSED");
        }
    });
    return rootView;

实现 View.OnClickListener 的 fragment

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
     View rootView = inflater.inflate(R.layout.fragment_summary_loggs, container, false);
     Button test = (Button) rootView.findViewById(R.id.testButton);
    test.setOnClickListener(this);

    return rootView;
}

    @Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.testButton:
            Log.e("DEBUGG", "BUTTON PRESSED");
            break;

    }
}

这只是我尝试过的许多例子中的两个,它让我发疯。在互联网上的所有例子中,他们都让他们工作。当我按下它们时,我的按钮根本不会响应。如果您能帮我解决这个问题,我将不胜感激。

布局文件

<FrameLayout 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" tools:context="xxxxxx.SummaryLoggs">

    <!-- TODO: Update blank fragment layout -->
    <TextView android:layout_width="match_parent" android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment3" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Test"
        android:id="@+id/testButton"
        android:layout_gravity="center" />
 </FrameLayout>

我滑动 fragment View 的 Activity

import...

public class AmLogger extends ActionBarActivity implements ActionBar.TabListener {


    SectionsPagerAdapter mSectionsPagerAdapter;
    Handler customHandler = new Handler();

   ViewPager mViewPager;

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

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {

            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_am_logger, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {        
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

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

        mViewPager.setCurrentItem(tab.getPosition());
    }

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

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

    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 PlaceholderFragment.newInstance(position + 1);

        }

        @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;
        }
    }


    public static class PlaceholderFragment extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }
        private int mPosition;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
               mPosition = getArguments().getInt(ARG_SECTION_NUMBER);   
           Log.e("DEBUGG", "mPosition: " + mPosition);

        }

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

            switch (mPosition) {
                case 1:
                   rootView = inflater.inflate(R.layout.fragment_add_time, container, false);
                    break;
                case 2:
                   rootView = inflater.inflate(R.layout.fragment_item_list, container, false);
                    break;
              }
            return rootView;
        }
    }
}

最佳答案

我认为您没有创建 3 个 fragment 。您的 Activity 中应该有 3 个 fragment 类,每个选项卡对应一个 fragment 类,而且根据每个 fragment 的设计,您需要有 3 个布局文件。然后在适当的布局文件中声明按钮,并在 Fragment 类中使用它,如下所示。

public class AmLogger extends ActionBarActivity implements ActionBar.TabListener {


    SectionsPagerAdapter mSectionsPagerAdapter;
    Handler customHandler = new Handler();

    ViewPager mViewPager;

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

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {@Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {

            actionBar.addTab(
            actionBar.newTab()
                .setText(mSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_am_logger, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

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

        mViewPager.setCurrentItem(tab.getPosition());
    }

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

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

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    // AddTime fragment
                    return AddTime.newInstance(position + 1);
                case 1:
                    // MyLogs fragment
                    return MyLogs.newInstance(position + 1);
                case 2:
                    // SummaryLogs fragment
                    return SummaryLogs.newInstance(position + 1);
            }
            return null;

        }

        @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;
        }
    }

    //AddTime fragment
    public static class AddTime extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";


        public static AddTime newInstance(int sectionNumber) {
            AddTime fragment = new AddTime();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public AddTime() {}

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

    //MyLogs Fragment
    public static class MyLogs extends Fragment {

        private static final String ARG_SECTION_NUMBER = "section_number";

        public static MyLogs newInstance(int sectionNumber) {
            MyLogs fragment = new MyLogs();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public MyLogs() {}

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

    //SummaryLogs fragment
    public static class SummaryLogs extends Fragment implements View.OnClickListener{

        private static final String ARG_SECTION_NUMBER = "section_number";

        public static SummaryLogs newInstance(int sectionNumber) {
            SummaryLogs fragment = new SummaryLogs();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public SummaryLogs() {}

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_summarylogs, container, false);
            //Code to get the button from layout file
            Button btn = (Button) rootView.findViewById(R.id.testButton);
            btn.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {
                    //Implement the code to run on button click here
                }
            });
            return rootView;
        }
    }

}

关于android - fragment 内的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30446818/

相关文章:

android - 如何从网站获取 vCard(.vcf 文件)到 Android 联系人中

java - 通过 Android 应用程序使用 Twitter4J 发布推文

html - 为什么 GIF 背景颜色是灰色而不是白色/透明?

Android fragment 事件监听器

java - Admob 广告不会显示在对话主题 Activity 中

excel - 有没有办法编辑表单控件按钮上的标题?

visual-studio - 为什么编译按钮在 Visual Studio 中被禁用?

android - 如何将 Parcelable 传递给两个或多个 Activity 或 Fragments?

android - getChildFragmentManager()无法解析或无法引用

java - ValueAnimator 只重复一次