-1
我想要將我的LinearLayout高度更改爲父佈局的50%,當我單擊按鈕。我使用LinearLayout.LayoutParams對它進行了修改,但如果我在onCreate之外的方法中使用buttonClicked方法調用時,它不會更改我的佈局的高度。但是,如果我將LinearLayout.LayoutParams放在onCreate中,那麼它就可以工作。我怎樣才能做到這一點,當我點擊一個按鈕?使用佈局之外的oncreate方法不起作用
此代碼:
public class ViewReport extends AppCompatActivity {
Button button;
LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_report);
button=(Button) findViewById(R.id.button);
layout=(LinearLayout) findViewById(R.id.fold);
final LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) layout.getLayoutParams();
lp.height = 0;
lp.width=LinearLayout.LayoutParams.MATCH_PARENT;
lp.weight=0.5f;
}
}
此代碼不起作用:
public class ViewReport extends AppCompatActivity {
Button button;
LinearLayout layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_report);
button=(Button) findViewById(R.id.button);
layout=(LinearLayout) findViewById(R.id.fold);
}
public void Click(View view)
{
Toast.makeText(getApplicationContext(),"tapped",Toast.LENGTH_LONG).show();
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) layout.getLayoutParams();
lp.height = 0;
lp.width=LinearLayout.LayoutParams.MATCH_PARENT;
lp.weight=0.5f;
}
}
佈局XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="me.imbishal.imageblur.ViewReport"
android:weightSum="1">
<LinearLayout
android:id="@+id/fold"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@drawable/profilepageback"
android:orientation="vertical">
<EditText
android:id="@+id/editText4"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginBottom="3dp"
android:background="@drawable/my_button"
android:ems="10"
android:inputType="textPersonName" />
<EditText
android:id="@+id/editText3"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginBottom="5dp"
android:background="@drawable/my_button"
android:ems="10"
android:inputType="textPersonName" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@drawable/just_border"
android:onClick="Click"
android:text="Button" />
</LinearLayout>
一個愚蠢的錯誤:(。我忘了設定的LayoutParams我的佈局。非常感謝。@KingintheNorth –