java - getView() 在第二个 Activity 中返回 null

标签 java android android-activity android-view

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

到目前为止,我只想在 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);
    }

我尝试了另外两种获取 View 对象的方法,但它们都不起作用:

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

View fragmentView = getView(); //neither

最佳答案

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.

因此,如果您想查找不在数据集上的 View ,例如在您的示例 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

关于java - getView() 在第二个 Activity 中返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010516/

相关文章:

java - 我和大O搞混了

java - 使用 spring mvc 提交/绑定(bind)部分对象

android - 用于推送移动服务的 SQL 数据库 Azure 收费

android - 线程会在 Android 中的 Activity 完成之前被杀死吗?

java - Proguard:将类成员保留在命名空间内

java - Spring Boot Actuator 端点在 SOAP Web 服务中无法访问

Android 删除所有行或更新并删除旧行?

android - 如何通过音频管理器以编程方式将振动模式更改为铃声

android - 为什么当用户单击确定时 onActivityResult() 返回 resultCode=0?

android - 从 BroadcastReceiver 启动 Activity