java - 如何解决Android中的静态 fragment 需求?

标签 java android android-fragments

我最近发现了类似于button.setText(“Hello World”);的代码行如果您按如下方式分配按钮,则 onCreate() 方法中将抛出 nullPointerException:

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

这是因为按钮所来自的 fragment 在分配按钮之前并未膨胀,从而使按钮为空。所以我了解到我需要将代码放在 fragment 扩展类中的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 类中会产生几个语法错误,指出“无法对非静态方法进行静态引用”。我尝试从 fragment 类中去掉静态,最后,它从一个问题变成了下一个问题。所以,我的问题是当这个代码块既不能在 onCreate() 也不能在 onCreateView() 中工作时,我应该如何实现它。 (请记住,整个代码块需要保持在一起)

fragment 类:

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

}

最佳答案

View (在您的例子中为“ActivityList”)直到调用 onCreateView() 后才会膨胀。

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

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

为了解决您遇到的静态问题,您必须准确地告诉我们您的代码中出现此问题的具体位置。

关于java - 如何解决Android中的静态 fragment 需求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24975832/

相关文章:

Android:TabActivity - 在 AsyncTask 完成之前不添加标签

android - 异常调度输入事件,同时调用 startActivity

android - 在 Activity 或 fragment 中初始化房间数据库?

java - JAXB - 从 Java 对象字段创建嵌套子元素

java - 功能: Image in a JFrame

java - 如何在 XWPFTableCell 中插入表格

java - 如何将 rowmapper 中的结果集转换为枚举?

java - ArrayList 根据 pojo 对象查找字段

Android Gradle 构建依赖错误

android - fragment - 全局 View 变量与本地和内部类监听器以及内存泄漏