根据下拉框的值显示/隐藏布局中的对象。

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

Show/hide objects in layout based on spinner value

问题

我创建了一个布局,顶部是一个带有两个选项的“Spinner”:相机和图库(显示为这个绿色的东西)。

当用户点击相机时,我希望它在下面打开一些其他对象,例如ImageView和按钮,就像这样:

根据下拉框的值显示/隐藏布局中的对象。

当用户点击图库时,我希望它显示为这样:

根据下拉框的值显示/隐藏布局中的对象。

我要提问的是如何在这两个布局之间切换?

据我了解,我可以使用:

setContentView(R.layout.activity_main);

Spinner spinner = findViewById(R.id.spinner);
if (spinner.getSelectedItem().toString().equals("相机")) {
     setContentView(R.layout.camera);
} else {
     setContentView(R.layout.gallery);
}

但是我怎么知道何时初始化这些对象?因为如果我尝试在内容为图库布局时使用:

Button button = findViewById(R.id.button1);

它找不到它并且会报错。

我知道我也可以将所有对象放在一个单独的布局中,并根据用户的选择来控制对象的可见性,但我想知道是否有一种更智能的方式来基于用户选择加载对象。

谢谢。

英文:

I created a layout that has at the top of it a Spinner with two options: Camera and Gallery (shown as this green thing).

When the user clicks on camera I had like it to open beneath the spinner few more objects such as ImageView and buttons like this:

根据下拉框的值显示/隐藏布局中的对象。

When the user clicks on Gallery I had like it to show like this:

根据下拉框的值显示/隐藏布局中的对象。

My question is how can I move between these two layouts?

From my understanding, I can use

setContentView( R.layout.activity_main );

Spinner spinner = findViewById( R.id.spinner);
if (spinner.getSelectedItem().toString().equals("camera")) {
     setContentView( R.layout.camera);
} else { setContentView( R.layout.gallery); }

But how do I know when to initialize the objects? because if I will try to use

Button button = findViewById( R.id.button1);

when it has the content of the gallery layout it won't find it and I will get an error.

I know I can also place all of the objects in a single layout and play with the visibility of the objects but I was wondering if there is a smarter way to load objects based on user choice.

Thank you

答案1

得分: 0

有很多不同的方法可以做到这一点,我可能会为您的每个布局(相机和相册)单独创建一个Fragment。然后在主布局中,您可以在Spinner下方放置一个FrameLayout,并在选择Spinner中的项目时将相应的Fragment加载到该框架中。

英文:

There are many different ways to do this, I would probably make a separate Fragment for each of your layouts (camera and gallery). Then in the main layout, you can put a FrameLayout below the Spinner and load the appropriate Fragment into that frame when an item in your Spinner is selected.

huangapple
  • 本文由 发表于 2020年7月27日 00:59:58
  • 转载请务必保留本文链接:https://java.coder-hub.com/63103157.html
匿名

发表评论

匿名网友

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

确定