我有很多次在片段中的按钮,但出于某种原因,我总是得到空指针。
我不知所措
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,尝试从片段活动实现onclicklistener,但没有任何效果。我到底做错了什么?
我在使用Android
发布于 2013-10-23 03:43:20
请检查片段和xml文件中使用的关闭按钮的id。
https://stackoverflow.com/questions/19531938
复制相似问题