【问题标题】:Button inside fragment片段内的按钮
【发布时间】:2015-08-07 10:26:20
【问题描述】:

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

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

没有实现View.OnClickListener的片段

 @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的片段

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

我滑动片段视图的活动

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

【问题讨论】:

  • 您是否尝试过调试或显示简单的Toast?也许您的 Logcat 输出有问题并且您的按钮可以正常工作?
  • 嗨。是的,我只需要为片段实现一个按钮。但是按钮不起作用。是的,我也试过用吐司。那也不行。
  • @user1512762 请同时显示您的片段布局文件。
  • 我也试过用吐司。 logcat 正在处理我的其他项目。 :)
  • 显示您在 Activity 中放置片段的位置。

标签: android button fragment


【解决方案1】:

我认为您没有创建 3 个片段。您的活动中应该有 3 个片段类,每个选项卡一个,并且根据每个片段的设计,您需要有 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;
        }
    }

}

【讨论】:

  • 谢谢!这行得通。虽然如果我在片段中添加代码,按钮不起作用。仅当我在每个片段部分下的活动中添加代码时。我想我可以在片段文件中添加按钮代码。无论如何,你的答案有效!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 2018-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多