The setOnclick Listener that I have written in the onCreate method doesn't work.
The error is a null pointer exception error for button b1. I tried to initialize b1 before the onclick method but it doesn't work either.
For this code I used the Android Studio Example "TAbbed Activity".
Then I'm searching a way to use the onClickListener method in a tabbed activity.
Please tell me some solutions . Thanks
public class MainActivity extends AppCompatActivity {
public static Button b1,b2;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// THIS DOESNT RUN AND IT MAKES THE APP CRASH
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b1.setText("test");
}
});
}
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;
}
public void newImageView(int sectionNumber, Button img, int n){
if(sectionNumber == n)
img.setVisibility(View.VISIBLE);
else
img.setVisibility(View.INVISIBLE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
b1=(Button)rootView.findViewById(R.id.b1);
newImageView(getArguments().getInt(ARG_SECTION_NUMBER),b1,1);
b2=(Button) rootView.findViewById(R.id.b2);
newImageView(getArguments().getInt(ARG_SECTION_NUMBER),b2,2);
return rootView;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
}
return null;
}
}
}`enter code here
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…