android - fragment 中的按钮 OnClick

标签 android android-fragments button tabs onclick

:) 我开始制作一个带有选项卡和 fragment 的应用程序,但是在 fragment 的类中,将 OnClick 添加到按钮时,按下按钮时没有任何反应

fragment_sub_page02.xml:

<LinearLayout 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="layout.SubPage02">
<Button
    android:id="@+id/button"

    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_margin="8dp"
    android:text="Button"
    />

这就是SubPage02.java:

public class SubPage02 extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Button mbutton;

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public SubPage02() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment SubPage02.
 */
// TODO: Rename and change types and number of parameters
public static SubPage02 newInstance(String param1, String param2) {
    SubPage02 fragment = new SubPage02();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    if (container == null) {
        return null;
    }

    LinearLayout mLinearLayout = (LinearLayout) inflater.inflate(R.layout.fragment_sub_page02,
            container, false);

    // note that we're looking for a button with id="@+id/myButton" in your inflated layout
    // Naturally, this can be any View; it doesn't have to be a button
    Button mButton = (Button) mLinearLayout.findViewById(R.id.button);
    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // here you set what you want to do when user clicks your button,
            // e.g. launch a new activity
        }
    });

    // after you've done all your manipulation, return your layout to be shown
    return mLinearLayout;
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 * <p>
 * See the Android Training lesson <a href=
 * "http://developer.android.com/training/basics/fragments/communicating.html"
 * >Communicating with Other Fragments</a> for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

在 onclick 中输入了一些内容后,什么也没发生...... 我应该把按钮的功能放在哪里...?

谢谢大家! :)

编辑1(MainActivity.java):

import java.util.zip.Inflater;
public class MainActivity extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
public FloatingActionButton fab;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // 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.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);


    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
            animateFab(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });


}
public static class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";


    public PlaceholderFragment() {
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
            View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
            return rootView;
        } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
            View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);
            return rootView;
        } else {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }
}

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) {
        switch (position) {
            case 0:
                return "AlertDialog";
            case 1:
                return "Toast";
            case 2:
                return "Snackbar";
        }
        return null;

    }


}

最佳答案

每次选择新页面时,TabLayout 都需要一个 PlaceholderFragment 的新实例,因此让我们仔细看看它的 onCreateView():

根据 getArguments().getInt(ARG_SECTION_NUMBER) 的值,特定布局会膨胀。如果值为 1,布局将与 SubPage02 相同。

但这并不意味着将创建 SubPage02 的实例,它们只是碰巧共享相同的布局文件。

因此必须在 PlaceholderFragmentonCreateView() 中设置 OnClickListener:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
        View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
        return rootView;
    } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
        View rootView = inflater.inflate(R.layout.fragment_sub_page02, container, false);

        Button mButton = (Button) rootView.findViewById(R.id.button);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // here you set what you want to do when user clicks your button,

            }
        });

        return rootView;
    } else {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }
}

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

相关文章:

android - React Native Maps - OnRegionChange 使 map 结结巴巴

android - OnClickListener 不适用于 fragment

java - 在 AsyncTask 完成之前不绘制 UI

android - 当我选择了 View 并向下滑动状态栏时,当我再次将其抬起时未选择 View

java - 构建配置语言和 Android Studio 中的语言有什么区别?

android - 在全屏android中打开图像

android - Google App Engine : DuplicateFileException

android - onBackPressed() 的问题不是刷新 fragment

c# - Windows Phone 8 按钮点击颜色

javascript - js函数被调用而不点击按钮