ふわふわぷかぷか

最近はイラレとAeにはまってます。

ボタンを押して、表示と非表示を切り替える。

前回は、画面を開いた時に非表示にしましたが、今回は、非表示にするボタンと表示するボタンを作って、切り替えができるようにします。

1つのボタンで切り替える方法はこちら

 

main.xmlはボタンを2つ増やしました。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#ffffff">

   
        <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="テキスト1" />
       
        <TextView
        android:id="@+id/text2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="テキスト2" />
       
        <TextView
        android:id="@+id/text3"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="テキスト3" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="非表示にする" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="表示する" />

</LinearLayout>

 次に、Activityでボタンのイベントを設定します。

public class ●●●Activity extends Activity implements OnClickListener {
    TextView tv1,tv2,tv3;
    Button button1,button2;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv1 = (TextView) findViewById(R.id.text1);
        tv2 = (TextView) findViewById(R.id.text2);
        tv3 = (TextView) findViewById(R.id.text3);
       
        button1 = (Button)findViewById(R.id.button1);
        button2 = (Button)findViewById(R.id.button2);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);     
     }

    public void onClick(View v) {
        if (v == button1){
            tv2.setVisibility(View.GONE);}
       
        if (v == button2){
            tv2.setVisibility(View.VISIBLE);}
        }}

これで、「非表示にする」ボタンを押すとテキスト2が消えて、「表示する」ボタンを押すとテキスト2が再び見えるようになります。

f:id:fuwafuwapukapuka:20140222075637j:plain  f:id:fuwafuwapukapuka:20140222075645j:plain

 テキスト2の幅を詰めないためには、「setVisibility(View.GONE);」を「setVisibility(View.INVISIBLE);」に変えればOKです。

 

1つのボタンで切り替える方法はこちら

 

初歩からわかるAndroid最新プログラミング 増補改訂版

初歩からわかるAndroid最新プログラミング 増補改訂版