【问题标题】:Changing text in EditText glitch更改 EditText 故障中的文本
【发布时间】:2019-02-10 22:43:26
【问题描述】:

在我的活动中,我有一个多行 EditText,因此用户可以存储一些注释:

<EditText
    android:id="@+id/notesTV"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="30dp"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="30dp"
    android:layout_marginEnd="30dp"
    android:layout_marginRight="30dp"
    android:background="@android:color/transparent"
    android:hint="Enter notes here..."
    android:inputType="textMultiLine"
    android:scrollbars="vertical"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">>
</EditText>

在代码中,我为此 EditText 创建了一个出口。然后我去我的数据库获取用户之前可能记过的任何笔记,并将这些笔记设置为 EditText 的文本。

package org1hnvc.httpshbssup.hbsnewventurecompetition;

import ...

public class Notes extends AppCompatActivity {

    private EditText notesTV;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Notes");

        notesTV = findViewById(R.id.notesTV);

        fetchNotes();
    }

    private void fetchNotes(){
        FirebaseManager.manager.fetchNotes(companyID, new FirebaseManager.NotesCallback() {
            @Override
            public void onSuccess(String notes) {
                notesTV.setText(notes);
            }

            @Override
            public void onError(String error) {
                Toast.makeText(getApplicationContext(), "An error occurred while fetching your notes",
                        Toast.LENGTH_LONG).show();
            }
        });
    }

}

当我这样做时,应用程序会发疯。它退出活动并转到上一个活动(我从中分离)。没有抛出错误,但显然代码没有正确执行。起初,我认为这可能与我的 fetchNotes 方法有关。但是,当我删除此方法并仅在 onCreate 方法中将 EditText 的文本设置为“测试”时,同样的事情发生了。有人请帮忙。

【问题讨论】:

    标签: android android-activity textview


    【解决方案1】:

    你的 Activity 因为这条线而崩溃:

    notesTV = findViewById(R.id.notesTV);
    

    您要求 Activity 按 Id“查找”视图,但您从未告诉它要膨胀哪个布局。

    进行如下更改:

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.the_layout_file_of_your_activity);
    
        setTitle("Notes");
    
        notesTV = findViewById(R.id.notesTV);
    
        fetchNotes();
    }
    

    尤其是setContentView() 部分。

    这样,Activity 将扩展布局并使其能够找到您的notesTV EditText。

    【讨论】:

      猜你喜欢
      • 2021-01-26
      • 1970-01-01
      • 2015-01-10
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      相关资源
      最近更新 更多