簡體   English   中英

無法使按鈕在片段中工作

[英]Cannot get buttons to work in fragments

對於Android和一般編程,我是一個完整的初學者。 試圖在所有地方找到解決方案,嘗試了所有解決方案,但從未成功,所以我放棄了,並決定發布此問題。 每次按下按鈕,應用都會崩潰。 我希望應用程序在按下按鈕時轉到任何片段。

看一下我在github中的代碼,並告訴我您的想法。

MainActivity.java

import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

import android.support.v4.app.FragmentTransaction;

import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    Fragment someFragment;

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


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    public void onClick(View v) {
        final int id = v.getId();

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        switch (id) {


            case R.id.button1:

                ft.replace(R.id.fragmenttab3, new FragmentTab3(), "fragment_screen");
                ft.commit();
                // your code for button1 here GOT TO FIND A WAY TO OUTPUT A MESSAGE WHEN CLICKED
                break;
            case R.id.button2:

                ft.replace(R.id.fragmenttab2, new FragmentTab2(), "fragment_screen");
                ft.commit();
                // your code for button2 here
                //DON'T FORGET TO ADD android:onClick="onClick" IN ACTIVITY_MAIN.XML BUTTON SEGMENT
                break;
            case R.id.button3:

                ft.replace(R.id.fragmenttab1, new FragmentTab1(), "fragment_screen");
                ft.commit();
                // your code for button3 here
                //DON'T FORGET TO ADD android:onClick="onClick" IN ACTIVITY_MAIN.XML BUTTON SEGMENT
                break;



        }

    }







    @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_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

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

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given 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;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    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); I COMMENTED THIS ONE OUT

            switch (position) {

                // Open FragmentTab1.java
                case 0:
                    FragmentTab1 fragmenttab1 = new FragmentTab1();
                    return fragmenttab1;

                // Open FragmentTab2.java
                case 1:
                    FragmentTab2 fragmenttab2 = new FragmentTab2();
                    return fragmenttab2;

                // Open FragmentTab3.java
                case 2:
                    FragmentTab3 fragmenttab3 = new FragmentTab3();
                    return fragmenttab3;
            }
            return null;



        }

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

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "SECTION 1";
                case 1:
                    return "SECTION 2";
                case 2:
                    return "SECTION 3";
            }
            return null;
        }
    }
}

FragmentTab2.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;





import android.support.v4.app.FragmentPagerAdapter;


import android.os.Bundle;



import android.support.v4.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import android.widget.Button;

public class FragmentTab2 extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Get the view from fragmenttab2.xml
        View view = inflater.inflate(R.layout.fragmenttab2, container, false);

        return view;
    }

}

fragmenttab2.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragmenttab2"
    android:layout_width="match_parent" android:layout_height="match_parent">



    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="@string/Fragment2" />


    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button2"
        android:onClick="onClick"

        android:layout_marginTop="13dp" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button3"
        android:onClick="onClick"


        android:layout_marginTop="69dp" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="56dp"
        android:layout_marginStart="56dp"
        android:layout_marginTop="51dp"
        android:onClick="onClick"
        android:text="@string/button1" />


</FrameLayout>

錯誤日志

05-25 13:04:56.928 2858-2858/com.example.guest3.swipetest E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.guest3.swipetest, PID: 2858
                                                                            java.lang.IllegalArgumentException: No view found for id 0x7f0d0089 (com.example.guest3.swipetest:id/fragmenttab1) for fragment FragmentTab1{1c4f0f6 #3 id=0x7f0d0089 fragment_screen}
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1293)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                                at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

您正在嘗試將片段放入活動的R.id.fragmenttab1容器中。 但是正如錯誤所言,Activity沒有這種觀點。

No view found for id 0x7f0d0089 (com.example.guest3.swipetest:id/fragmenttab1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM