微调 Android Studio 中导航更改时的下拉列表项丢失问题。

huangapple 未分类评论46阅读模式
英文:

Spinner items lost on navigate change in Android Studio

问题

MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        // Rest of the code...
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Rest of the code...

        PublicCameras Cameras = new PublicCameras();
        Spinner dropdown = findViewById(R.id.cameraList);
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, Cameras.GetNamesEn());
        dropdown.setAdapter(adapter);

        return true;
    }

    // Rest of the code...
}

FirstFragment

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });
    }
}

SecondFragment

public class SecondFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_second, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_second).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(SecondFragment.this)
                        .navigate(R.id.action_SecondFragment_to_FirstFragment);
            }
        });
    }
}

You can use ViewModel to store and manage data that should survive configuration changes. This way, you can retain the spinner's values across fragment transitions and other layout changes.

英文:

I have created an Android Studio project and i have MainActivity, FirstFragment and SecondFragment. On the FirstFragment I have an spinner element. When the app starts the spinner is filled with values, when I switch from the First to the second Fragment and back, the values are gone.

MainActivity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, &quot;Replace with your own action&quot;, Snackbar.LENGTH_LONG)
                        .setAction(&quot;Action&quot;, null).show();
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        PublicCameras Cameras = new PublicCameras();
        //get the spinner from the xml.
        Spinner dropdown = findViewById(R.id.cameraList); // This element loses his values when navigating to SecondFragment and back
        ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;&gt;(this, android.R.layout.simple_spinner_dropdown_item, Cameras.GetNamesEn());
        dropdown.setAdapter(adapter);
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

FirstFragment

public class FirstFragment extends Fragment {

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {


        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);



        view.findViewById(R.id.button_first).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(FirstFragment.this)
                        .navigate(R.id.action_FirstFragment_to_SecondFragment);
            }
        });
    }
}

SecondFragment

public class SecondFragment extends Fragment {

    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_second, container, false);
    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        view.findViewById(R.id.button_second).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavHostFragment.findNavController(SecondFragment.this)
                        .navigate(R.id.action_SecondFragment_to_FirstFragment);
            }
        });
    }
}

I would like to point out that on rotating the values are being set again because of re-entering the function onCreateOptionsMenu. What is the best practice to keep values on a layout change?

Thank you for your time !

答案1

得分: 0

你遇到这个问题是因为当你从一个片段移动到另一个片段时,安卓会销毁该片段,然后在返回时重新创建该片段,屏幕方向发生变化时也会出现这种情况。为了处理这个问题,在你的代码中重写OnSavedInstance方法。

这里有一个小技巧可以让它正常工作。

首先重写:

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArray("YOUR_KEY", "YOUR_OBJECT"); // 将这里的内容替换为你的对象名称
}

然后在你的onViewCreated方法中使用SavedInstance变量,使用相应的键获取该字符串数组,然后将其传递给Spinner。

你可以尝试这样做,如果遇到任何问题,请在评论中说明。

英文:

You're getting this issue cause when you move from one fragment to other android destorys the fragment and recreates that fragment when returned back this happens in the screen orientation case too. In order to handle this override OnSavedInstance method in you're code

There is a little hack you can make it work.

first override

@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArray(&quot;YOUR_KEY&quot;, &quot;YOUR_OBJECT&quot;);//chnage this with you&#39;re object name
}

Now in you're onViewCreated use the SavedInstance variable and get that stringArray using the key and pass this to the spinner.

Try this and if you faced any issue do comment.

huangapple
  • 本文由 发表于 2020年7月26日 19:44:51
  • 转载请务必保留本文链接:https://java.coder-hub.com/63099687.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定