片段中的按钮在Android Studio中无法点击

时间:2018-12-16 02:02:54

标签: android android-fragments button

我正在尝试使按钮从片段布局转到xml文件。但是,在运行该应用程序时,我无法单击该按钮。我已经检查过我是否必须更正ID。就是这种情况。有人知道答案为何不会触发我的onClickListener()吗?我觉得我想念的东西很小,但是我不知道到底是什么。谢谢 !

我的课:

default

我的xml在布局文件夹中:

public class AccountFragment extends Fragment {
    private FragmentActivity myContext;
    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;
    private View RootView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    public void onAttach(Activity activity) {
        myContext=(FragmentActivity) activity;
        super.onAttach(activity);
    }

        private static final String TAG = AccountFragment.class.getSimpleName();
        private static final String ARG_SECTION_NUMBER = "section_number";
        public static final int TAB_PRIVATE = 1;
        public static final int TAB_CORP = 2;

        public AccountFragment() {
        }

        public static AccountFragment newInstance(int sectionNumber) {
            AccountFragment fragment = new AccountFragment();
            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) {

            RootView = inflater.inflate(R.layout.fragment_account, container, false);

            Log.i(TAG, "onCreateView()");

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

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

            //BUTTON
            Button openSettingsButton = RootView.findViewById(R.id.open_settings);

            openSettingsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(getContext(), PreferenceFragmentAccount.class);
                    startActivity(i);
                }
            });

            return RootView;
        }

        @Override
        public void onResume() {
            Log.i(TAG, "onResume()");
            super.onResume();
            View view = getView();
            if (view == null) {
                Log.e(TAG, "view is null!");
                return;
            }
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
            String username=null;
            String email=null;
            String firstname=null;
            String lastname=null;
            String phoneNumber=null;

                username = sharedPreferences.getString(USERNAME, null);
                email = sharedPreferences.getString(EMAIL, null);
                firstname = sharedPreferences.getString(FIRSTNAME, null);
                lastname = sharedPreferences.getString(LASTNAME, null);
                phoneNumber = sharedPreferences.getString(PHONE, null);


            ImageView qrCode = view.findViewById(R.id.qr);
            qrCode.setImageDrawable(getResources().getDrawable(R.drawable.ic_hourglass_full_teal_24dp));

            if (TextUtils.isEmpty(username)) {
                username = getString(R.string.no_name);
            }

            VCard vCard = new VCard(username)
                    .setEmail(email)
                    .setName(firstname + lastname)
                    .setPhoneNumber(phoneNumber);

            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            view.getHeight();
            Display display = wm.getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int qrSize = (int) (0.8 * (double) Math.min(size.x, size.y));

            setTextToTextViewOrHide(username, R.id.username, view);
            setTextToTextViewOrHide(email, R.id.email, view);
            setTextToTextViewOrHide(firstname, R.id.firstname, view);
            setTextToTextViewOrHide(lastname, R.id.lastname, view);
            setTextToTextViewOrHide(phoneNumber, R.id.phoneNumber, view);

            new SetQrCodeTask().execute(new SetQrCodeTaskBundle(vCard, qrSize));




        }

        private void setTextToTextViewOrHide(String value, @IdRes int id, View view) {
            TextView textView = view.findViewById(id);
            if (TextUtils.isEmpty(value)) {
                textView.setVisibility(View.GONE);
            } else {
                textView.setText(value);
            }
        }

        private class SetQrCodeTaskBundle {
            private VCard mVCard;
            private int mQrSize;

            SetQrCodeTaskBundle(VCard vCard, int qrSize) {
                mVCard = vCard;
                mQrSize = qrSize;
            }

            VCard getVCard() {
                return mVCard;
            }

            int getQrSize() {
                return mQrSize;
            }
        }

        private class SetQrCodeTask extends AsyncTask<SetQrCodeTaskBundle, Void, Bitmap> {
            private final String TAG = SetQrCodeTask.class.getSimpleName();

            @Override
            protected Bitmap doInBackground(SetQrCodeTaskBundle... setQrCodeTaskBundles) {
                Log.d(TAG, "Generate QR code");
                return QRCode
                        .from(setQrCodeTaskBundles[0].getVCard())
                        .withColor(0xFF000000, 0x00000000)
                        .withSize(setQrCodeTaskBundles[0].getQrSize(), setQrCodeTaskBundles[0].getQrSize())
                        .withHint(EncodeHintType.CHARACTER_SET, "UTF-8")
                        .bitmap();
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                Log.d(TAG, "Set QR code");
                ImageView qrCode = getView().findViewById(R.id.qr);
                qrCode.setImageBitmap(bitmap);
            }
        }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

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

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

2 个答案:

答案 0 :(得分:0)

我已经在Android Studio上检查了您的代码,代码完美无缺,但是您在父级 RelativeLayout 上方将 Viewpager 设置为一个错误 匹配父项,因此您不会获得单击按钮的权利,但是如果将Viewpager重构到按钮下方,您将能够获得单击。

这是您可以做的。我已经安装了AndroidX,因此代码在其中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true">


        <android.support.v7.widget.CardView
            android:id="@+id/cardView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="12dp"
            android:layout_marginRight="12dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <android.support.constraint.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/username"
                    style="@style/TextAppearance.AppCompat.Large"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:icon="@drawable/ic_person_teal_24dp"
                    android:inputType="textPersonName"
                    android:summary="%s"
                    android:textColor="@color/primary_dark"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    tools:text="Name" />

                <TextView
                    android:id="@+id/email"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="6dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/username"
                    tools:text="E-mail" />

                <TextView
                    android:id="@+id/firstname"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="6dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/email"
                    tools:text="First name" />

                <TextView
                    android:id="@+id/lastname"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="6dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="1.0"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/firstname"
                    tools:text="Last name" />


                <TextView
                    android:id="@+id/phoneNumber"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="8dp"
                    android:layout_marginLeft="8dp"
                    android:layout_marginTop="6dp"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@id/lastname"
                    tools:text="phoneNumber" />


                <View
                    android:id="@+id/view"
                    android:layout_width="0dp"
                    android:layout_height="8dp"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toBottomOf="@+id/phoneNumber"
                    tools:ignore="MissingConstraints" />
            </android.support.constraint.ConstraintLayout>

        </android.support.v7.widget.CardView>


        <Button
            android:id="@+id/open_settings"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="10dp"
            android:text="@string/open_settings"
            tools:layout_editor_absoluteX="8dp"
            tools:layout_editor_absoluteY="43dp" />

        <ImageView
            android:id="@+id/qr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginBottom="24dp"
            android:contentDescription="@string/qr_code"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/open_settings"
            app:srcCompat="@drawable/ic_hourglass_full_teal_24dp" />

        <androidx.viewpager.widget.ViewPager
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="554dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"
            tools:layout_editor_absoluteY="105dp" />
    </androidx.constraintlayout.widget.ConstraintLayout>


</RelativeLayout>

答案 1 :(得分:0)

为什么不使用butterknife

添加到gradle->

  

实现'com.jakewharton:butterknife:9.0.0-rc2'

     

annotationProcessor'com.jakewharton:butterknife-compiler:9.0.0-rc2'

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

                RootView = inflater.inflate(R.layout.fragment_account, container, false);
                ButterKnife.bind(this, RootView );
                ...
                return RootView;
            }

    @OnClick(R.id.open_settings)
    public void btn(){
                                Intent i = new Intent(getContext(), PreferenceFragmentAccount.class);
                        startActivity(i);
    }

okey,因此您可以像这样更改源:

Button openSettingsButton;
 @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            RootView = inflater.inflate(R.layout.fragment_account, container, false);

            Log.i(TAG, "onCreateView()");

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

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

            //BUTTON
            openSettingsButton = RootView.findViewById(R.id.open_settings);


            return RootView;
        }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
            openSettingsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(getContext(), PreferenceFragmentAccount.class);
                    startActivity(i);
                }
            });
    }