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 を使用する代わりに、一度に 1 つの子のみを表示するビュー フリッパーの子として、画面の 2 つのレイアウトを追加します。また、表示する子のインデックスを指定できます。ビュー フリッパーを使用する利点は、ビューを切り替えるときにアニメーションが必要な場合に、ビューの「イン」アニメーションと「アウト」アニメーションを簡単に指定できることです。これは、 setContentView を何度も呼び出すよりもはるかにクリーンな方法です。

于 2011-09-19T23:19:38.833 に答える
2

FrameLayoutハンドルはこれを素晴らしく処理します...これをcontstructと一緒に使用して、他の複数のレイアウトをロードします。次に、個々のレイアウトを使用し<include...て、それらを切り替えることができます。setvisibility(View.VISIBLE);setVisibility(View.INVISIBLE);

例えば:

他の2つのレイアウトを含むメイン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 に答える