作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在开发一个应用程序,用户应该能够通过按下其他按钮来改变按钮的外观。我使用四个按钮设置高度作为包装内容、高度作为填充父级、宽度作为包装内容和宽度作为填充父级。
我在谷歌上搜索了一下,找到了一个使用 LayoutParams 的解决方案,尽管该代码没有指定高度和宽度是否被改变。我还收到错误消息,说我的 IDE 无法识别“LayoutParams”。执行此操作的最佳方法是什么?
最佳答案
您需要查找的是 View.ViewGroup.LayoutParams。每个 LayoutParams 都具有 MATCH_PARENT 和 WRAP_CONTENT 属性的常量值。我准备了您可以玩的简单代码示例:
Activity :
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>
关于java - 将按钮高度和宽度设置为包装内容并填充父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11694945/
我是一名优秀的程序员,十分优秀!