java match parent_java – 将按钮高度和宽度设置为包装内容并填充父级

你需要寻找的是View.ViewGroup.LayoutParams.

每个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:

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical" >

android:layout_height="wrap_content"

android:layout_width="match_parent"

android:orientation="horizontal">

android:id="@+id/button1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="h_wc" />

android:id="@+id/button2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="w_wc" />

android:id="@+id/button3"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="h_fp" />

android:id="@+id/button4"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="h_fp" />

android:id="@+id/test"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="test" />

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值