以编程方式为定义的方案设置按钮不可见

时间:2014-02-05 11:26:24

标签: android android-linearlayout

我在布局中有两个按钮,水平放置在一起。我想隐藏第一个按钮并将第二个按钮放在linearlayout的中心。 我使用了下面的代码,但它并没有满足要求。

if (flag){

  btn1.setVisibility(View.GONE); //.setEnabled(false);

  android.widget.LinearLayout.LayoutParams params = new    android.widget.LinearLayout.LayoutParams(
  LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 2f);
  params.setMargins(15, 0, 15, 0);

  btn2.setLayoutParams(params);
 }else{
  btn1.setVisibility(View.VISIBLE); //.setEnabled(true);
}

请建议。 感谢。

在xml文件中,两个按钮应该水平相邻,如果隐藏一个按钮,则第二个按钮应该水平居中。而且我也在使用linearlayout。

2 个答案:

答案 0 :(得分:0)

保留xml文件并在您的activity和setVisibility中调用该按钮,而不是动态创建布局

答案 1 :(得分:0)

尝试使用此xml文件

<?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="horizontal" >

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

<LinearLayout
    android:id="@+id/parent"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button2" />
</LinearLayout>

</LinearLayout>

活动

LinearLayout parent = (LinearLayout) findViewById(R.id.parent);

if (flag){

   btn1.setVisibility(View.GONE);
   parent.setGravity(Gravity.CENTER_HORIZONTAL);

 }else{

 btn1.setVisibility(View.VISIBLE);
 parent.setGravity(Gravity.LEFT);
}