我的片段中有多次按钮,但由于某种原因,我一直得到空指针。
我不知所措
FragmentActivity
public class WelcomeBase extends FragmentActivity {
FragmentAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_base);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new FragmentAdapter(getSupportFragmentManager(), getApplicationContext());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
}
片段
public class FragmentThree extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private String mContent = "Page3";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(ARG_SECTION_NUMBER)) {
mContent = savedInstanceState.getString(ARG_SECTION_NUMBER);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.welcome_page3, container, false);
Button close = (Button) root.findViewById(R.id.close_helper);
close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getActivity(), MainActivity.class);
startActivity(intent);
}
});
return root;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(ARG_SECTION_NUMBER, mContent);
}
}
这是片段xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/transparent"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:baselineAligned="false"
android:textAlignment="gravity"
android:gravity="center_vertical"
android:clickable="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/welcome_close"
android:layout_gravity="center" />
</LinearLayout>
空指针在这一行
close.setOnClickListener(new View.OnClickListener() {
我已尝试从xml布局实现onclick,我尝试从fragmentactivity实现onclicklistener并且没有任何效果。世界上我可能做错了什么?
我正在使用Android Studio
答案 0 :(得分:0)
请检查片段和xml文件中使用的关闭按钮的ID。