3

想要制作一个以布局开头的 Android 应用程序,当您按下此布局中的按钮(称为stateButton)时,布局更改为包含另一个按钮(称为boton2 )的main2布局,当您按下此按钮时,您会得到回到第一主线。

我想在同一个活动中执行此操作,而不创建或启动另一个活动。

在这里,我向您展示部分代码:

public class NuevoshActivity extends Activity
implements SensorEventListener, OnClickListener {
    private Button stateButton;
    private Button boton2;

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState);       
        setContentView(R.layout.main); 
        this.stateButton = (Button) this.findViewById(R.id.boton);
        this.boton2 = (Button) this.findViewById(R.id.boton2);      
        stateButton.setOnClickListener(this);
        boton2.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v==stateButton) {
            setContentView(R.layout.main2);             
        }
        else if(v==boton2) {
            setContentView(R.layout.main);
        }
    }
}

主电源只有一些图像、文本视图和按钮。

但我有一些麻烦。不能就这么简单吗?或者我错过了什么或出了什么问题?

4

4 回答 4

4

当您使用 findViewById 时,您实际上是在尝试在 setContentView 指定的布局内查找视图。因此,当您尝试检查按钮时,一次又一次地使用 setContentView 可能会带来问题。

我不会使用 setContentView,而是将屏幕的 2 个布局添加为一个视图翻转器的子布局,它一次只显示一个孩子。您可以指定要显示的子项的索引。使用视图翻转器的好处是,如果在视图之间切换时需要动画,您可以轻松地为视图指定“进”和“出”动画。这是一个更简洁的方法,然后一次又一次地调用 setContentView。

于 2011-09-19T23:19:38.833 回答
2

处理得FrameLayout非常好......使用它与构造一起加载多个其他布局,然后您可以通过使用和在各个布局上<include...来回切换它们。setvisibility(View.VISIBLE);setVisibility(View.INVISIBLE);

例如:

主要 XML 包括其他两个布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:id="@+id/frameLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">
    <include android:id="@+id/buildinvoice_step1_layout" layout="@layout/buildinvoice_step1" android:layout_width="fill_parent" android:layout_height="fill_parent"></include>
    <include android:id="@+id/buildinvoice_step2_layout" android:layout_width="fill_parent" layout="@layout/buildinvoice_step2" android:layout_height="fill_parent"></include>
</FrameLayout>

在布局之间切换的代码:

findViewById(R.id.buildinvoice_step1_layout).setVisibility(View.VISIBLE);
findViewById(R.id.buildinvoice_step2_layout).setVisibility(View.INVISIBLE);

您还需要在活动开始时(或在 XML 中)设置各个布局的可见性,否则您将同时看到它们 - 一个在另一个之上。

于 2011-09-19T22:49:36.407 回答
1

您的boton2按钮将为 NULL,因为按钮的定义位于main2.xml. 您将能够找到的唯一视图是在 中定义的视图main.xml

于 2011-09-19T22:55:16.540 回答
0

谢谢!!!所有信息对于理解很多事情都很有用,正如 C0deAttack 评论的那样,我在 main2 上的按钮遇到了麻烦。我所做的是将 View.VISIBLE 和 View.GONE 设置为我在每个布局中想要的 TextViews 和 Buttons。非常感谢你。

于 2011-09-20T15:01:17.690 回答