我如何获取MainActivity.java类文件之外的任何小部件的ID?

时间:2019-06-15 18:20:42

标签: java android

为此,我想从MySQL数据库中获取信息并将其显示在ListView中,为此我在名为“ BackgroundWorker.java”的单独类中编写了代码。我正在从数据库中获取所有内容,但是我不知道如何在“ BackgroundWorker”类中获取布局文件的TextView小部件的ID以显示结果。

MainActivity.java代码

new BackgroundWorker(this).execute()

BackgroundWorker.java代码

protected void onPostExecute(String result) {
    //here i want to get id of layout widget to display result
}

1 个答案:

答案 0 :(得分:0)

对于此类问题,Android提供了WeakReference,如果您可以操纵此类,便可以获取任何所需的引用

private static class SampleTask extends AsyncTask<Integer, Integer, String>{
    private WeakReference<MainActivity> activityReference;
    MainActivity activity;

    SampleTask(MainActivity context)
    {
        activityReference = new WeakReference<>(context);

    }

    //....
    @Override
    protected void onPostExecute(String s)
    {
        super.onPostExecute(s);
        activity = activityReference.get();
        if (activity == null || activity.isFinishing())
        {
            return;
        }
        //Now you have the activity you can access your fields including 

    }
}

Visit here了解更多详细信息