我正在开发一个应用程序,用户应该可以通过按其他按钮来改变按钮的外观.我使用四个按钮将高度设置为换行内容,将高度设置为填充父级,将宽度设置为换行内容,将宽度设置为填充父级.
我用Google搜索了一下,并找到了使用LayoutParams的解决方案,尽管该代码没有指定是否更改了宽度的高度.我也有错误说我的IDE无法识别“LayoutParams”.做这个的最好方式是什么?
解决方法
你需要寻找的是View.ViewGroup.LayoutParams.
每个LayoutParams都具有MATCH_PARENT和WRAP_CONTENT属性的常量值.
我已准备好您可以使用的简单代码示例:
每个LayoutParams都具有MATCH_PARENT和WRAP_CONTENT属性的常量值.
我已准备好您可以使用的简单代码示例:
活动:
- package com.example.stack2;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.view.ViewGroup.LayoutParams;
- import android.widget.Button;
- public class MainActivity extends Activity implements OnClickListener{
- Button test;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- Button b = (Button)findViewById(R.id.button1);
- b.setOnClickListener(this);
- b = (Button)findViewById(R.id.button2);
- b.setOnClickListener(this);
- b = (Button)findViewById(R.id.button3);
- b.setOnClickListener(this);
- b = (Button)findViewById(R.id.button4);
- b.setOnClickListener(this);
- test = (Button)findViewById(R.id.test);
- }
- public void onClick(View v)
- {
- LayoutParams lp = test.getLayoutParams();
- if(v.getId() == R.id.button1)
- {
- lp.height = LayoutParams.WRAP_CONTENT;
- }else if(v.getId() == R.id.button2){
- lp.width = LayoutParams.WRAP_CONTENT;
- }else if(v.getId() == R.id.button3){
- lp.height = LayoutParams.MATCH_PARENT;
- }else if(v.getId() == R.id.button4){
- lp.width = LayoutParams.MATCH_PARENT;
- }
- test.setLayoutParams(lp);
- }
- }
布局xml:
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- <LinearLayout
- android:layout_height="wrap_content"
- android:layout_width="match_parent"
- android:orientation="horizontal">
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="h_wc" />
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="w_wc" />
- <Button
- android:id="@+id/button3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="h_fp" />
- <Button
- android:id="@+id/button4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="h_fp" />
- </LinearLayout>
- <Button
- android:id="@+id/test"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="test" />
- </LinearLayout>