"findViewById 返回 null (TextView)"

18 浏览
0 Comments

"findViewById 返回 null (TextView)"

此问题已有答案:

NullPointerException accessing views in onCreate()

findViewById in Fragment

我已经在谷歌和StackOverflow上搜索了,但是没有一个解决方案能够解决我的问题。

在onCreate()中使用findViewById返回null。

但是,当我将其更改为onClick函数时,它可以正常工作。

请帮帮我,我是一个初学者。

我的MainFunction.java

public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
    final TextView t = (TextView) findViewById(R.id.textView1);
    t.setText("hi world.");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}
@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 {
    public PlaceholderFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        return rootView;
    }
}

}

我的fragment_main.xml

admin 更改状态以发布 2023年5月23日
0
0 Comments
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container,
            false);
    TextView t = (TextView) rootView.findViewById(R.id.textView1);
    t.setText("hi world.");
    return rootView;
}

(不需要翻译)

0
0 Comments

你的 TextView 在片段 (fragment_main.xml) 中,并且你正在查看 R.layout.activity_main。所以最好在你的FragmentPlaceholderFragment 中编写findViewById。或者你可以使用 Inflater 来获取你的 fragment_layout,然后使用 view.findViewById 来获取你的 TextView

0