ImageButton 不适用于 Fragments,单击 ImageButton 时崩溃

ImageButton not working with Fragments , Crashes when Click ImageButton

问题:我的 FragmentHome 上有一个 ImageButton,我正在尝试实现该按钮以打开 AddEntry 片段,以便用户可以将信息添加到数据库中。每次我点击它崩溃的 ImageButton :/

我仍在学习 Android Studio/Java 这是我第一次开发应用程序。

再次感谢

LogCat:

   04-06 01:10:12.873 5449-5449/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               Process: com.example.treycoco.calorietracker, PID: 5449
                                                                               java.lang.IllegalStateException: Could not find method Click(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageButton with id 'AddItems'
                                                                                   at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:325)
                                                                                   at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                                                                                   at android.view.View.performClick(View.java:5697)
                                                                                   at android.view.View$PerformClick.run(View.java:22526)
                                                                                   at android.os.Handler.handleCallback(Handler.java:739)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                   at android.os.Looper.loop(Looper.java:158)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

更新LogCat:

             04-06 01:32:18.745 30188-30188/com.example.treycoco.calorietracker E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                 Process: com.example.treycoco.calorietracker, PID: 30188
                                                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getId()' on a null object reference
                                                                                     at com.example.treycoco.calorietracker.FragmentHome.onClick(FragmentHome.java:61)
                                                                                     at android.view.View.performClick(View.java:5697)
                                                                                     at android.view.View$PerformClick.run(View.java:22526)
                                                                                     at android.os.Handler.handleCallback(Handler.java:739)
                                                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                     at android.os.Looper.loop(Looper.java:158)
                                                                                     at android.app.ActivityThread.main(ActivityThread.java:7229)
                                                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

fragment_home.xml

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
        xmlns:fab="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
       android:layout_height="match_parent"
           android:background="@color/colorBackground"

        tools:context="layout.HomeFragment"
           android:id="@+id/HomeFragment">



       <LinearLayout
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:weightSum="1"
             android:id="@+id/linearLayout">


      <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
  android:text="Welcome,"
   android:id="@+id/textView"

   android:layout_alignParentTop="true"
   android:layout_alignParentStart="true" />

                  <TextView
                      android:layout_width="138dp"
                 android:layout_height="36dp"
               android:textAppearance="?android:attr/textAppearanceLarge"
                 android:text="@string/emptyString"
                 android:id="@+id/User"
                  android:layout_gravity="center_horizontal|top"
                  android:layout_alignParentTop="true"
               android:layout_centerHorizontal="true" />

                  <TextView android:id="@+id/section_label"
                                  android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="left"
android:layout_below="@+id/linearLayout2"
android:layout_centerHorizontal="true" />
 </LinearLayout>

   <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="355dp"
    android:layout_gravity="center|bottom">

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/listView"
        android:layout_gravity="center_horizontal"
        android:layout_alignParentBottom="true"
        android:layout_alignParentStart="true" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/AddItems"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:src="@drawable/add"
        android:background="@color/colorBackground"
        android:onClick="Click"
        android:clickable="true" />
   </RelativeLayout>


</FrameLayout>

FragmentHome.java

                   public class FragmentHome extends Fragment implements
                      View.OnClickListener  {

           public static final String ARG_SECTION_NUMBER = "section_number";
           public static final String ARG_ID = "_id";
            private TextView label;
            private int sectionNumber = 0;
           private Calendar fragmentDate;
            ListView  listview;
            ImageButton AddEntrybtn;
         CalorieDatabase calorieDB;
            private View v;


         private android.support.v4.app.FragmentManager fragmentManager;
      private FragmentTransaction fragmentTransaction;

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


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

      View myView = inflater.inflate(R.layout.fragment_home, container,
         false);


   label= (TextView) myView.findViewById(R.id.section_label);



          return myView;


       }


        @Override
          public void onActivityCreated(Bundle savedInstanceState) {
          super.onActivityCreated(savedInstanceState);

            Bundle username = getActivity().getIntent().getExtras();



         String username1 = username.getString("Username");

         TextView userMain= (TextView) getView().findViewById(R.id.User);

        userMain.setText(username1);

       AddEntrybtn = (ImageButton)getView().findViewById(R.id.AddItems);

       openDataBase();

         }



          private  void openDataBase (){


          calorieDB= new CalorieDatabase(getActivity());
            calorieDB.open();


           }


             private void closeDataBase(){
              calorieDB.close();
          };


         private  void populateLVFromDB(){

           Cursor cursor = calorieDB.getAllRows();




    String[] fromFieldNames = new String[]
            {CalorieDatabase.KEY_NAME, CalorieDatabase.KEY_CalorieValue};
    int[] toViewIDs = new int[]
            {R.id.foodEditText,     R.id.caloriesEditText,           };


    SimpleCursorAdapter myCursorAdapter =
            new SimpleCursorAdapter(
                    getActivity(),      
                   R.layout.row_item,
                    cursor,                  
                    fromFieldNames,         
                    toViewIDs                
            );

  listview = (ListView) getActivity().findViewById(R.id.listView);
    listview.setAdapter(myCursorAdapter);


}












@Override
public void onResume() {
    super.onResume();
    // set label to selected date.  Get date from Bundle.
    int dayOffset = sectionNumber - FragmentHomeDayViewPager.pagerPageToday;
    fragmentDate = Calendar.getInstance();
    fragmentDate.add(Calendar.DATE, dayOffset);
    SimpleDateFormat sdf = new SimpleDateFormat(appMain.dateFormat);

    String labelText = sdf.format(fragmentDate.getTime());
    switch (dayOffset) {
        case 0:
            labelText += " (Today)";
            break;
        case 1:
            labelText += " (Tomorrow)";
            break;
        case -1:
            labelText += " (Yesterday)";
            break;
    }
    label.setText(labelText);

}















@Override
public void onDestroy() {
    super.onDestroy();

}



@Override
public void onDetach() {
    super.onDetach();

    startActivity( new Intent(getContext(),MainActivity.class));
}


@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.AddItems:

            AddEntry addEntry    = new AddEntry();

            fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.addToBackStack(null);
            fragmentTransaction.replace(R.id.FragmentHolder,addEntry)

                    .commit();


            break;
         }


     }
    }

appMain.java

          public class appMain extends AppCompatActivity implements
          AdapterView.OnItemClickListener {



         private  ActionBarDrawerToggle actionBarDrawerToggle;
       public static String dateFormat = "E MMM d yyyy";
         private DrawerLayout drawerLayout;
      private ListView drawerList;
     private android.support.v4.app.FragmentManager fragmentManager;
       private FragmentTransaction fragmentTransaction;





    @Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.app_main);



    drawerLayout=(DrawerLayout)findViewById(R.id.drawerlayout);

    drawerList= (ListView) findViewById(R.id.drawerList);
    ArrayList<String> ListArray= new ArrayList<String>();
    ListArray.add("home");
    ListArray.add("Add Calories");
    ListArray.add("Bmi Tracker");
    ListArray.add("About App");
    ListArray.add("Settings");
    ListArray.add("Logout");

    drawerList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

    ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_activated_1,ListArray);
    drawerList.setAdapter(adapter);
    drawerList.setOnItemClickListener(this);








    actionBarDrawerToggle=new ActionBarDrawerToggle(this,drawerLayout,R.string.navigation_drawer_open,
            R.string.navigation_drawer_close);

    drawerLayout.setDrawerListener(actionBarDrawerToggle);


    ActionBar actionBar= getSupportActionBar();
    actionBar.setDisplayShowHomeEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);





    String username = getIntent().getStringExtra("Username");
    TextView userMain = (TextView) findViewById(R.id.User);
    userMain.setText(username);


     fragmentManager=getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();
    loadSelection(0);




}

private  void loadSelection(int i){
    drawerList.setItemChecked(i,true);


        switch (i) {
            case 0:
             FragmentHome  homeFragment    = new FragmentHome();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(R.id.FragmentHolder, homeFragment)

                        .commit();
                break;


            case 1:

                AddEntry addEntry    = new AddEntry();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(R.id.FragmentHolder,addEntry)

                        .commit();

                break;




            case 2:
BmiFrag myBiFragment = new BmiFrag();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);

fragmentTransaction.replace(R.id.FragmentHolder, myBiFragment)


.commit();
         break;


            case 3:

              AboutApp aboutApp    = new AboutApp();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(R.id.FragmentHolder, aboutApp)

                        .commit();


                break;



            case 4 :



                break;

            }

}


@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    actionBarDrawerToggle.syncState();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.menu_main, menu);

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

      int id=item.getItemId();

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

        if(drawerLayout.isDrawerOpen(drawerList)){

            drawerLayout.closeDrawer(drawerList);
        }
        else {

            drawerLayout.openDrawer(drawerList);

        }

    }


    return super.onOptionsItemSelected(item);

}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    switch (position){
        case 0:

            loadSelection(position);
            break;


        case  1:
            loadSelection(position);

            break;

        case 2:
            loadSelection(position);
            break;

        case 3:
            loadSelection(position);
            break;

        case 4:

            loadSelection(position);

            break;


        case  5:
            Intent i = new Intent(this, MainActivity.class);
            startActivity(i);
            break;


    }

    drawerLayout.closeDrawer(drawerList);
}



public void setTitle(String title) {

    getSupportActionBar().setTitle(title);
}



public void ButtonClick  (View v) {



    switch (v.getId()) {





        case R.id.BtnBMi:




            break;


    }


}

}

第一次删除 android:onClick="Click"

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/AddItems"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:src="@drawable/add"
    android:background="@color/colorBackground"
    />

然后

ImageButton btn = (ImageButton) myView.findViewById(R.id.AddItems);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {

                // Add your Staff

                }
            });

将此添加到您的 View onCreateView 部分。

把onClick里面的代码拿出来

    case R.id.AddItems:

        AddEntry addEntry    = new AddEntry();

        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.addToBackStack(null); 
        fragmentTransaction.replace(R.id.FragmentHolder,addEntry)

                .commit(); 


        break; 
     } 

并将其放在方法 Click 中。

例如:

  private void Click{

        AddEntry addEntry    = new AddEntry();

        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.addToBackStack(null); 
        fragmentTransaction.replace(R.id.FragmentHolder,addEntry)

                .commit(); 

}

首先:删除xml中的行 android:onClick="Click"

二:在onActivityCreated中移除行

AddEntrybtn = (ImageButton) getView().findViewById(R.id.AddItems);

三:在onCreateView中调用

AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(this);

在片段fragment_home代码中:

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/AddItems"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:src="@drawable/add"
    android:background="@color/colorBackground"
    />

在HomeFragment.java

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

      View myView = inflater.inflate(R.layout.fragment_home, container,
         false);


   label= (TextView) myView.findViewById(R.id.section_label);

ImageButton btn = (ImageButton) myView.findViewById(R.id.AddItems);
            btn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View arg0) {
//Call the Activity method where you add fragments
                ((appMain)getActivity()).loadSelection(4);

                }
            });

          return myView;


       }

添加方法appMain.java

 public  void loadSelection(int i){
        drawerList.setItemChecked(i,true);


        switch (i) {
            case 0:
                FragmentHome  homeFragment    = new FragmentHome();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(R.id.FragmentHolder, homeFragment)

                        .commit();
                break;


            case 1:

                AddEntry addEntry    = new AddEntry();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(R.id.FragmentHolder,addEntry)

                        .commit();

                break;




            case 2:
                BmiFrag myBiFragment = new BmiFrag();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);

                fragmentTransaction.replace(R.id.FragmentHolder, myBiFragment)


                        .commit();
                break;


            case 3:

                AboutApp aboutApp    = new AboutApp();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(R.id.FragmentHolder, aboutApp)

                        .commit();


                break;



            case 4 :

                AddEntry addEntry    = new AddEntry();

                fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.addToBackStack(null);
                fragmentTransaction.replace(R.id.FragmentHolder,addEntry)

                        .commit();


                break;

        }

    }