getView() returns 第二个为空 activity

getView() returns null in second activity

我有一个构建捆绑包并将其传递给第二个 activity 的应用程序,以便稍后使用捆绑包中的数据。

到目前为止,我只想在 TextView 中显示 bundle 中的一个元素,以确保我可以处理 activity 中的数据。我正在调用 getView().findViewByID(R.id.theTextViewIWant),但它总是返回 null,并且 IDE 表示无法解析 getView()。我相信它必须是我对持有第二个 activity 的 View 不完全理解的东西,所以我很感激任何帮助。

public class MyClass extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mark_student);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }

    @Override
    protected void onStart(){
        super.onStart();

        Bundle receivedInfo = getIntent().getExtras();
        String unitSelected = receivedInfo.getString("key");

        TextView textViewBox = (TextView) getView().findViewById(R.id.textView2);
        textViewBox.setText(unitSelected);
    }

我已经尝试了另外两种获取视图对象的方法,但它们都没有用:

ViewGroup rootView = (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0); //nope

View fragmentView = getView(); //neither

IDE 告诉你 getView() 不是 Activity 方法(但是它是 Fragment method). In an Activity you can simply call findViewById().

TextView textViewBox = (TextView) findViewById(R.id.textView2);

I'm calling getView().findViewByID(R.id.theTextViewIWant), but it is always returning null, and the IDE says it cannot resolve getView()

我建议你阅读 getView() 方法文档,但有一个小的解释

Get a View that displays the data at the specified position in the data set.

因此,如果您想查找不在数据集上的视图,例如在您的示例 TextView 中,那么您想使用 findViewById(int)

Finds a view that was identified by the android:id XML attribute that was processed in onCreate(Bundle).

正如文档中所说,我建议您将其放在 onCreate() 方法上,而不是 onStart().

然后你必须删除 getView() 并像这样:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.yourLayoutFromActivity2);
  TextView textViewBox = (TextView) findViewById(R.id.textView2);
}

注意:如果你把你的东西放在 onStart() 中,这意味着每次来自前台的应用程序都会执行你在其中的所有内容。我也建议你看看Android life cycle

getView() 是片段方法。您需要在 activity 中使用 findViewById() 来初始化视图。还将初始化代码移动到 onCreate 方法并在那里处理意图。