При перезапуске активности из другой активности LinearLayout активности пуст - PullRequest
0 голосов
/ 02 мая 2020

Моя Main активность отображается нормально, как и при запуске приложения. Он получает записи базы данных и отображает их. Кроме того, при запуске другого действия, действия Edit и переходе назад с помощью кнопки назад, все выполняется, как указано выше. Однако, когда я выполняю этот код из действия Edit:

Intent intent = new Intent(this, Main.class);

intent.setAction(Intent.ACTION_VIEW);
startActivity(intent);

Операция Main пуста, код основного действия:

public class Main extends Base {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initDB(); // Just a database check if it is there, works always
    initFAB(); // FAB is visible as normal all the time, also when coming from Edit
    processIntent();
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

@Override
protected void onResume() {
    super.onResume();
}

@Override
protected void onPause() {
    super.onPause();
}

@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    processIntent();
}

/**
 * Processes the intent.
 */
private void processIntent() {
    Intent intent = getIntent();

    if (intent.getAction().equals(Intent.ACTION_MAIN) || intent.getAction().equals(Intent.ACTION_VIEW)) {
        if (intent.hasExtra(Intent.EXTRA_REPLACING))
            Toast.makeText(this, intent.getIntExtra(Intent.EXTRA_REPLACING, 0), Toast.LENGTH_LONG).show();
        else if (intent.hasExtra(Intent.EXTRA_RETURN_RESULT))
            Toast.makeText(this, intent.getStringExtra(Intent.EXTRA_RETURN_RESULT), Toast.LENGTH_LONG).show();

        queryAllNotes();
    }
  }
}

Я делаю рендеринг в другом классе с доступом к действию Main, код рендеринга теперь из-за следующих попыток отладки с комментариями: queryAllNotes() получает аргумент notes из базы данных, который работает:

/**
 * Renders all note wrappers.
 */
public void all(ArrayList<Note> notes) {
    final boolean noneFound = notes.size() < 1;

    if (noneFound) // Remove views
        remove();

    main.updateNoNotesText(noneFound);

    final ScrollView scrollView = remove();
    final LinearLayout linearLayout = new LinearLayout(main);

    linearLayout.setOrientation(LinearLayout.VERTICAL);
    linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    scrollView.addView(linearLayout);

    for (int i = 0; !noneFound && i < notes.size(); i++) {
        if (i < linearLayout.getChildCount() && i < links.size()) { // Reuse views
            links.get(i).setNote(notes.get(i), i);
        } else { // Create new views
            LayoutInflater.from(main).inflate(R.layout.note, linearLayout, true);
            links.add(new NoteViewLink(notes.get(i), (RelativeLayout) linearLayout.getChildAt(linearLayout.getChildCount() - 1), i));
        }
    }

    // DEBUGGING:
    //        scrollView.setVisibility(View.GONE);
    //        scrollView.setVisibility(View.VISIBLE);
    //        scrollView.invalidate();
    //        scrollView.refreshDrawableState();

    for (int i = 0; i < scrollView.getChildCount(); i++) {
        LinearLayout v = (LinearLayout) scrollView.getChildAt(i);

        //            v.setVisibility(View.GONE);
        //            v.setVisibility(View.VISIBLE);
        //            v.invalidate();

        for (int j = 0; j < v.getChildCount(); j++) {
            RelativeLayout rl = (RelativeLayout) v.getChildAt(j);
            Log.d("debug", j + " RL: " + isShown(rl) + " " + rl.getVisibility() + "/" + View.VISIBLE + " LL: " + isShown(v) + " " + v.getVisibility() + "/" + View.VISIBLE);
            // App Start Log Output:
            // D/debug: 0 RL: true 0/0 LL: true 0/0
            // ...
            // D/debug: 50 RL: true 0/0 LL: true 0/0
            // Main Activity Start from Edit activity Log Output:
            // D/debug: 0 RL: false 0/0 LL: false 0/0
            // ...
            // D/debug: 50 RL: false 0/0 LL: false 0/0
        }
    }

    //        scrollView.requestLayout();
}

public boolean isShown(View current) {
    //noinspection ConstantConditions
    do {
        if (current.getVisibility() != View.VISIBLE) {
            return false;
        }
        ViewParent parent = current.getParent();
        if (parent == null) {
            return false; // We are not attached to the view root
        }
        if (!(parent instanceof View)) {
            return true;
        }
        current = (View) parent;
    } while (current != null);

    return false;
}

/**
 * Removes all views.
 *
 * @return For convenience the note scroll view.
 */
public ScrollView remove() {
    final ScrollView scrollView = main.findViewById(R.id.scrollView);
    scrollView.removeAllViews();
    links.clear();
    return scrollView;
}

.xml из Main - это:

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <ScrollView
    android:id="@+id/scrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="gone">

    <!--LinearLayout is created programmatically in all()-->
   </ScrollView>
 </RelativeLayout>

Я скопировал метод isShown(View current) из класса Android View, чтобы иметь возможность пройти через рекурсию, он идет вверх в DecorView, который входит в первый if в isShown(View current), возвращающем false, что не имеет никакого смысла для меня, весь верхний закомментированный код не работал, также не на моем LinearLayout и его дочерних элементах, RelativeLayouts.

Как отобразить содержимое действия Main при запуске Main из действия Edit? Я не могу понять, что отличается, он запрашивает все notes из базы данных при запуске приложения и должен просто отобразить их соответственно при запуске приложения. Я не должен касаться DecorView, а только ScrollView, содержащегося LinearLayout или его дочерних элементов RelativeLayouts, которые все видны и работают при запуске приложения.

...