单击按钮时的Android setlayout可见性

时间:2012-08-25 20:47:54

标签: android android-layout android-intent android-emulator

在以下代码中单击按钮我想隐藏相对布局rl1并显示rl2但是我的应用程序在点击按钮后崩溃了。我做错了什么

 <?xml version="1.0" encoding="utf-8"?>

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
<RelativeLayout 
android:id="@+id/rl1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/welcome_1">

    <ImageView
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"

        android:paddingTop="360dp"
        android:layout_marginRight="4dp"
        android:src="@drawable/button1" />

     </RelativeLayout>

    <RelativeLayout
        android:id="@+id/rl2"
         android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:visibility="invisible"
     android:background="@drawable/menu_2"
        ></RelativeLayout>
     </RelativeLayout>

Java代码

public class mockupsActivity extends Activity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


 // ImageButton img1 = (ImageButton)findViewById(R.id.button1);
    ImageView img1 =(ImageView)findViewById(R.id.button1);
    img1.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
           // your code here
   //       Toast.makeText(TouchpointmockupsActivity.this, "test", Toast.LENGTH_SHORT).show();
            LinearLayout rl1 = (LinearLayout) findViewById(R.id.rl1);
            rl1.setVisibility(View.INVISIBLE);
            LinearLayout rl2 = (LinearLayout) findViewById(R.id.rl2);
            rl2.setVisibility(View.VISIBLE);
        }
    });





}
}

1 个答案:

答案 0 :(得分:5)

在代码中将LinearLayout更改为RelativeLayout。您可能会收到classcastException。

编辑: 更改OnClick方法如下

        RelativeLayout rl1 = (RelativeLayout) findViewById(R.id.rl1);
        rl1.setVisibility(View.INVISIBLE);
        RelativeLayout rl2 = (RelativeLayout) findViewById(R.id.rl2);
        rl2.setVisibility(View.VISIBLE);