在我的片段中,每当我单击按钮时,它的可见性就会更改为“消失”。 我希望旋转屏幕时能见度保持不变。 我正在使用onSaveInstanceState,但希望获得有关outState添加内容的帮助。
任何帮助将不胜感激,谢谢!
public class PlaylistsFragment extends Fragment {
private Button add1;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_playlists, container, false);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.
}
@Override
public void onViewCreated(final View view, @Nullable final Bundle savedInstanceState) {
final Button add1 = (Button) getView().findViewById(R.id.p_add1);
add1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
add1.setVisibility(View.GONE);
}
});
}
}
答案 0 :(得分:0)
尝试一下:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
savedInstanceState.putInt("button_visibility", add1.getVisibility());
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
myButtonVisibility = savedInstanceState.getInt("button_visibility", 0);
}
例如onCreate中的
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add1 = (Button)findViewById(R.id.p_add1);
if (savedInstanceState != null) {
int buttonVisibility = savedInstanceState.getInt("button_visibility", 0);
// here will IDE complaint about setting only integer
add1.setVisibility(buttonVisibility == View.VISIBLE ? View.VISIBLE : View.GONE)
}
}
如果您还有其他疑问,请务必阅读本教程: saveInstanceState tutorial
享受。