编辑:
我是android的新手,我尝试在我的应用中使用片段。我尝试在我的活动中使用片段函数,但我得到一个空指针异常..
片段:
public class VideoviewFragment extends Fragment {
private View card;
public static VideoviewFragment create() {
return new VideoviewFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_videoview, container, false);
card = (View) view.findViewById(R.id.card_video);
return view;
}
public void setalphacard(float value){
card.setAlpha(value);
}
}
在主要活动中,我希望这样做(我简化了我的代码):
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Viewpager
final SmartFragmentStatePagerAdapter adapterViewPager;
final ViewPager viewPager = (ViewPager) findViewById(R.id.am_view_pager);
adapterViewPager = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapterViewPager);
final VideoviewFragment videoviewFragment = (VideoviewFragment) adapterViewPager.getRegisteredFragment(2);
videoviewFragment.setalphacard(0.3f);
}
}
主要寻呼机适配器:
public class MainPagerAdapter extends SmartFragmentStatePagerAdapter {
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return CameraFragment.create();
case 1:
return OptionFragment.create();
case 2:
return VideoviewFragment.create();
}
return null;
}
@Override
public int getCount() {
return 3;
}
}
答案 0 :(得分:1)
您只需要像这样全局声明View
:
public class VideoviewFragment extends Fragment {
private View card;
public static VideoviewFragment create() {
return new VideoviewFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_videoview, container, false);
card = (View) view.findViewById(R.id.card_video);
return view;
}
public void setalphacard(float value){
card.setAlpha(value);
}
}
答案 1 :(得分:0)
在片段中全局声明您的View对象。