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

时间:2014-07-26 21:49:32

标签: java android android-fragments

我最近发现了类似于button.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()来解决问题,但是将此代码放在fragment类中会产生一些语法错误,说“无法对非staic方法进行静态引用”。我尝试从片段类中取走静态,最后,它从一个问题转到另一个问题。所以,我的问题是当它既不在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);

}

1 个答案:

答案 0 :(得分:1)

在调用onCreateView()之后,视图(在您的情况下&#34; ActivityList&#34;)不会被充气。

所以在onCreate()中,它是null。

您必须将此代码块放在onCreateView()或onViewCreated()中(在视图正确膨胀后立即调用onViewCreated)。

要解决您遇到的静态问题,您必须告诉我们您的代码中出现此问题的确切位置。