如何围绕在Android的静态片段的要求



我最近发现了类似于按钮的代码行。setText("Hello World");在onCreate()方法将抛出一个nullPointerException,如果你这样分配按钮:

 Button button=(Button)findViewById(R.id.myLayout); 

这是因为按钮来自的片段在分配按钮之前没有被充气,因此使按钮为空。因此,我了解到我需要将代码放在片段扩展类的onCreateView()方法中。但是,在我目前正在制作的应用程序中,我在onCreate():

中实现此代码
 SharedPreferences activitiesFile = getApplicationContext().getSharedPreferences("Activities", 0);
    Set<String> keylist = activitiesFile.getAll().keySet();
    for (String s : keylist) {
        String active = activitiesFile.getString(s, "");
        Button activeName=new Button(this);
        activeName.setText(active);
        activeName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
                LayoutParams.WRAP_CONTENT));
        LinearLayout layout=(LinearLayout) findViewById(R.id.ActivityList);
        activeName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FillInInfo(v);
            }
        });
        layout.addView(activeName);
    }

一切都是这个代码块工作完全正常,除了layout.addView(activeName);因为我之前提到的nullPointerException。所以,我决定把这个代码块放入onCreateView()来解决这个问题,但是把这个代码放在片段类中会产生几个语法错误,说"不能对非静态方法进行静态引用"。我试着从片段类中拿走静态,最后,它从一个问题到下一个问题。所以,我的问题是我应该如何实现这个代码块,当它既不onCreate()也不onCreateView()工作。(请记住,这整个代码块需要保持在一起)

片段类:

 public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    /**
     * Returns a new instance of this fragment for the given section number.
     */
    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 PlaceholderFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_manage_day,
                container, false);

        TextView textView = (TextView) rootView
                .findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((ManageDay) activity).onSectionAttached(getArguments().getInt(
                ARG_SECTION_NUMBER));
    }
}
整个类代码:
 public class ManageDay extends ActionBarActivity implements
    NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
 * Fragment managing the behaviors, interactions and presentation of the
 * navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
 * Used to store the last screen title. For use in
 * {@link #restoreActionBar()}.
 */
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_manage_day);
    Intent intent=getIntent();
    SharedPreferences activitiesFile = getApplicationContext().getSharedPreferences("Activities", 0);
    Set<String> keylist = activitiesFile.getAll().keySet();
    for (String s : keylist) {
        String active = activitiesFile.getString(s, "");
        Button activeName=new Button(this);
        activeName.setText(active);
        activeName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
                LayoutParams.WRAP_CONTENT));
        LinearLayout layout=(LinearLayout) findViewById(R.id.ActivityList);
        activeName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FillInInfo(v);
            }
        });
        layout.addView(activeName);
    }

    mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();
    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager
            .beginTransaction()
            .replace(R.id.container,
                    PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
    switch (number) {
    case 1:
        mTitle = getString(R.string.title_section1);
        break;
    case 2:
        mTitle = getString(R.string.title_section2);
        break;
    case 3:
        mTitle = getString(R.string.title_section3);
        break;
    }
}
public void restoreActionBar() {
    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.manage_day, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}
@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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";
    /**
     * Returns a new instance of this fragment for the given section number.
     */
    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 PlaceholderFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_manage_day,
                container, false);

        TextView textView = (TextView) rootView
                .findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(
                ARG_SECTION_NUMBER)));
        return rootView;
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((ManageDay) activity).onSectionAttached(getArguments().getInt(
                ARG_SECTION_NUMBER));
    }
}

public void CreateActivity(View view){
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String activity = editText.getText().toString();
    Button button=new Button(this);
    button.setText(activity);
    LinearLayout layout=(LinearLayout) findViewById(R.id.ActivityList);
    button.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FillInInfo(v);
        }
    });
    layout.addView(button);
    editText.setText("");
    SharedPreferences activitiesFile = getApplicationContext().getSharedPreferences("Activities", 0);   
    SharedPreferences.Editor editor = activitiesFile.edit();
    editor.putString(activity, activity);
    editor.apply();
}
public void FillInInfo(View view){
    Intent intent=new Intent(this,ActivityInfo.class);
    Button button=(Button)view;
    String buttonName=button.getText().toString();
    intent.putExtra("Name",buttonName);
    startActivity(intent);
}

视图(在您的情况下"ActivityList")不会膨胀,直到onCreateView()被调用。

所以在onCreate()中,它是空的

你必须把这个代码块放在onCreateView()或onViewCreated() (onViewCreated是在视图正确膨胀后被调用)。

为了解决你遇到的静态问题,你必须准确地告诉我们你的代码在哪里出现了这个问题

最新更新