Android-我在哪里设置eventListener在选项卡中的按钮



我有一个塔巴固定性和其中一些选项卡。在其中一个选项卡中(标签的名称为 HomeTab)是一个按钮。我希望按钮做点什么。因此,我已经在SectionsPagerAdapter -> getItem(int position)方法中设置了按钮的EventListener。但是它返回一个NullPoInterException。我应该在哪里设置EventListener,以便findViewById()不会返回null

mainActivity.java:

package com.whatsyouridea.myapp;
import android.content.Intent;
import android.support.design.widget.TabLayout;
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.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TimePicker;
import java.util.TimerTask;
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;
    @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);
    }

    @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);
    }
    public void start_timer_for_timer(int hours, int minutes, int seconds) {
    }
    public void start_timer_for_clock(TimePicker time_picker) {
    }
    public void start_btn_clicked(View view) {
        RadioGroup radioGroup = (RadioGroup)view.findViewById(R.id.selection_buttons);
        int selectedIndex = ComponentTools.getSelectedRadioButtonIndex(view, radioGroup);
    }
    public void stop_btn_clicked() {
    }
    /**
     * 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) {
            switch (position) {
                case 0:
                    HomeTab homeTab = new HomeTab();
                    /**************Here is where the error occured***************/
                    // Set up start button EventListener
                    Button start_button = (Button)homeTab.getView().findViewById(R.id.start_btn);
                    start_button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Button start_button = (Button)view.findViewById(R.id.start_btn);
                            start_button.setEnabled(false);
                            Button stop_button = (Button)view.findViewById(R.id.stop_btn);
                            stop_button.setEnabled(true);
                            start_btn_clicked(view);
                        }
                    });
                    // Set up stop button EventListener
                    Button stop_button = (Button)homeTab.getView().findViewById(R.id.stop_btn);
                    stop_button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Button start_button = (Button)view.findViewById(R.id.start_btn);
                            start_button.setEnabled(true);
                            Button stop_button = (Button)view.findViewById(R.id.stop_btn);
                            stop_button.setEnabled(false);
                            stop_btn_clicked();
                        }
                    });
                    return homeTab;
                case 1:
                    TimerSettingsTab timerSettingsTab = new TimerSettingsTab();
                    return timerSettingsTab;
                case 2:
                    ClockSettingsTab clockSettingsTab = new ClockSettingsTab();
                    return clockSettingsTab;
                default:
                    return null;
            }
        }
        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }
        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "HOME";
                case 1:
                    return "TIMER SETTINGS";
                case 2:
                    return "CLOCK SETTINGS";
            }
            return null;
        }
    }
}

hometab.java(fragment java class)

package com.whatsyouridea.myapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HomeTab extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tab_home, container, false);
        return rootView;
    }
}

完整错误:

09-14 07:56:20.852 8483-8483/com.whatsyouridea.myapp E/AndroidRuntime: FATAL EXCEPTION: main
         Process: com.whatsyouridea.myapp, PID: 8483
         java.lang.RuntimeException: Unable to start activity ComponentInfo{com.whatsyouridea.myapp/com.whatsyouridea.myapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
             at android.app.ActivityThread.access$800(ActivityThread.java:151)
             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
             at android.os.Handler.dispatchMessage(Handler.java:102)
             at android.os.Looper.loop(Looper.java:135)
             at android.app.ActivityThread.main(ActivityThread.java:5254)
             at java.lang.reflect.Method.invoke(Native Method)
             at java.lang.reflect.Method.invoke(Method.java:372)
             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
          Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
             at com.whatsyouridea.myapp.MainActivity.onCreate(MainActivity.java:66)
             at android.app.Activity.performCreate(Activity.java:5990)
             at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
             at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
             at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
             at android.app.ActivityThread.access$800(ActivityThread.java:151) 
             at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
             at android.os.Handler.dispatchMessage(Handler.java:102) 
             at android.os.Looper.loop(Looper.java:135) 
             at android.app.ActivityThread.main(ActivityThread.java:5254) 
             at java.lang.reflect.Method.invoke(Native Method) 
             at java.lang.reflect.Method.invoke(Method.java:372) 
             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 

选项卡1

做这个

 // inside the onCreateView method of the fragment 
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
  Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_home, container, false);
  Button myButton= (Button) rootView.findViewById(R.id.button);
  myButton.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
      //  do something..
     }});
return rootView;
}

或此..

// implements OnClickListener interface
public class HomeFragment extends BaseFragment  implements OnClickListener {
 private Button myButton;
@Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    myButton= (Button) rootView.findViewById(R.id.button);
    // set the listen to the contex 
    myButton.setOnClickListener(this);
    return rootView;
  }
// override onClick and check using switch
 @Override
  public void onClick(View view) {
    switch (view.getId()) {
      case R.id.button:
         // do something
        break;
     }
  }
}

最新更新