简体   繁体   English

如何解决Android中的静态片段要求?

[英]How to around the static fragment requirements in Android?

I recently figured out that lines of code similar to button.setText("Hello World"); 我最近发现,这些代码行类似于button.setText(“ Hello World”);。 in the onCreate() method will throw a nullPointerException if you assigned the button as so: 如果按如下方式分配按钮,则onCreate()方法中的方法将抛出nullPointerException:

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

This is because of the fact that the fragment the button came from wasn't inflated before the button was assigned, thus making the button null. 这是因为,在分配按钮之前,来自按钮的片段并未被夸大,因此使按钮为空。 So I learned that I need to put the code in the onCreateView() method in the fragment extension class. 因此,我了解到需要将代码放入片段扩展类的onCreateView()方法中。 But, in the app I am currently making, I am implementing this code in the onCreate(): 但是,在我当前正在制作的应用程序中,我正在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);

    }

Everything is this code block works completely fine, except for the layout.addView(activeName); 除了layout.addView(activeName);之外,此代码块的所有内容都可以正常工作。 because of the nullPointerException I mentioned before. 由于我之前提到的nullPointerException。 So, I decided to put this code block into the onCreateView() to fix the problem, but putting this code in the fragment class creates a couple of syntax errors saying "can not make a static reference to a non-staic method". 因此,我决定将此代码块放入onCreateView()中以解决此问题,但是将此代码放入片段类会产生一些语法错误,即“无法静态引用非静态方法”。 I tried taking away the static from the fragment class, and in the end, it went from one problem to the next. 我尝试从片段类中删除静态对象,最后,它从一个问题转移到下一个问题。 So, my question is how should I implement this code block when it works in neither onCreate() nor onCreateView(). 因此,我的问题是,当该代码块无法在onCreate()或onCreateView()中工作时,应如何实现该代码块。 (Keep in mind that this whole code block needs to stay together) (请记住,整个代码块必须保持在一起)

Fragment Class: 片段类别:

 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));
    }
}

The whole class code: 整个类代码:

 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);

}

The view (in your case "ActivityList") doesn't get inflated untill after onCreateView() is called. 在调用onCreateView()之后,视图(在您的情况下为“ ActivityList”)不会膨胀。

So in onCreate(), it is null. 因此在onCreate()中,它为null。

You'll have to put this code block in onCreateView() or onViewCreated() (onViewCreated is called right after the view is correctly inflated). 您必须将此代码块放在onCreateView()或onViewCreated()中(在正确放大视图之后立即调用onViewCreated)。

To combat the static problem you're having, you'll have to tell us exactly WHERE you're having this problem in your code. 为了解决您遇到的静态问题,您必须确切地告诉我们代码中出现此问题的位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM