【问题标题】:Add Text to TextView while AsyncTask Running在 AsyncTask 运行时向 TextView 添加文本
【发布时间】:2020-08-22 12:09:36
【问题描述】:

我正在学习AsyncTask。我想在 AyncTask 工作时添加像 Loading.... 这样的 TextView。我该怎么做呢

下面是代码

public class MainActivity extends AppCompatActivity {
private EditText et_bookInput;
private TextView tv_titleText;
private TextView tv_authorText;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    et_bookInput = findViewById(R.id.bookInput);
    tv_titleText = findViewById(R.id.titleText);
    tv_authorText = findViewById(R.id.authorText);

}

public void searchBooks(View view) {
    // Get the name of the book from the input field
    String queryString = et_bookInput.getText().toString();
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if(inputMethodManager != null){
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
    new FetchBook(tv_titleText, tv_authorText).execute(queryString);

}

【问题讨论】:

  • 可以为 FetchBook 添加代码吗?您是否尝试过使用 onPreExecute 和 onPostExecute 函数?此外,AsyncTask 不再是在 Android 上执行异步任务的首选方式,Android 推荐使用协程。
  • 据我所知,Corountines 是 Kotlin 库,所以我可以在 java 代码中使用它吗?

标签: android android-asynctask


【解决方案1】:

试试下面的代码:

 tv_authorText.setText("");
 tv_titleText.setText(R.string.loding);

我假设您想在tv_titleText 添加加载文本。

【讨论】:

    【解决方案2】:

    我已经测试了你的代码,你需要在 searchBooks(View view) 中设置 loading 文本

    TextView.setText("Loading...")
    

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多