【问题标题】:How to change ContentView when a button is clicked?单击按钮时如何更改 ContentView?
【发布时间】:2015-06-09 15:30:05
【问题描述】:

大家好, 我需要帮助更改 MainActivity 中的 ContentView(不更改 Activity)。 我想显示“特别感谢”。其中有一些帮助我本地化和测试应用程序的用户名。 为此,我使用了一个带有

的按钮
android:onClick="onSpcThxButtonClick"

我要显示的xml叫做“spcthx.xml”

我需要你完成以下代码:

public void onSpcThxButtonClick (View view)
{
        // insert ContentView switch here
}

希望你能帮助我。

提前致谢!

【问题讨论】:

  • setContentView(R.layout.spcthx);
  • @dymmeh 否。Eclipse 说 setContentView 不存在(即使它在 onCreate 中有效)。
  • @dymmeh(未知方法“setContentView”)

标签: java android android-layout setcontentview


【解决方案1】:

仅调用 setcontentview 函数就不能轻松使用 setcontentview。您可以使用 Framelayout 删除所有视图并膨胀新布局以更改/切换不同的视图。我希望这会有所帮助。

【讨论】:

  • 嗯。好的。谢谢你。如果没有人知道不同的答案,那么调用不同的活动会更容易。
  • 或者是的,您可以调用另一个活动并调用 setContentView。但是您的目标是在按下按钮时动态更改而不丢失活动,对吗?
  • 是的。因为我希望用户能够只按手机上的返回键,而不是使用“返回”按钮重新启动 MainActivity。
  • 哦。我认为这就是解决方案。但是,如果没有人建议更容易编码,请尝试我的建议。我会帮你。祝你好运。
【解决方案2】:

试试这个。

<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".Settings" >

<!-- Settings  -->
<LinearLayout
    android:id="@+id/settings_form"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    >

</LinearLayout>

<!-- Special Thanks -->
<LinearLayout 
    android:id="@+id/special_thanks_form"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:visibility="gone"
    >


</LinearLayout>

然后在您的 Activity 上仅引用它们

private View            settingsForm;
private View            specialThanksForm;

settingsForm      = findViewById(R.id.settings_form);
specialThanksForm = findViewById(R.id.special_thanks_form);

然后在按钮 clickListener 上更改视图的可见性

settingsForm.setVisibility(View.GONE);
specialThanksForm.setVisibility(View.VISIBLE);

【讨论】:

  • 我会稍微修改你的建议,虽然我在 main.xml 中有两个按钮,非常感谢!
  • 是的,我只是在解释一般情况..很高兴它有帮助
猜你喜欢
  • 2021-03-19
  • 2018-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 2021-07-21
  • 2013-07-24
相关资源
最近更新 更多