【问题标题】:Android setlayout visibility on button click按钮单击时的 Android setlayout 可见性
【发布时间】:2012-08-25 20:47:54
【问题描述】:

在单击按钮的以下代码中,我想隐藏相对布局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);
        }
    });





}
}

【问题讨论】:

  • 你应该阅读你的 logcat,它会告诉你你做错了什么。或者至少发布它,以便其他人可以看到堆栈跟踪。 :)

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


【解决方案1】:

在您的代码中将 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);

【讨论】:

  • 检查编辑。布局具有RelativeLayout,但您将其转换为LinearLayout
  • @Rajeev Hes 谈论 rl1 和 rl2。您将它们作为相关布局,但将它们转换为线性布局。
  • 不确定。使 relativelayout 可见以检查背景在正常情况下是否可见。检查 menu_2 是否存在。此外,如果您希望不可见的布局在布局中不占用空间,则最好使用 View.GONE 而不是 View.INVISIBLE
猜你喜欢
  • 2020-08-10
  • 2017-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多