私は、ユーザーが他のボタンを押すことでボタンの外観を変更できるはずのアプリケーションを開発しています。4つのボタンを使用して、高さを折り返しコンテンツ、高さを塗りつぶし親、幅を折り返しコンテンツ、幅を塗りつぶし親として設定します。
私は少しググって、LayoutParamsを使用した解決策を見つけましたが、そのコードは幅の高さが変更されたかどうかを指定していませんでした。また、IDEが「LayoutParams」を認識できないというエラーも発生しました。これを行うための最良の方法は何ですか?
探す必要があるのは、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:
<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>
以下のコードを使用すると、高さと幅を動的に簡単に変更できます。
btn = new Button(Activity.this);
btn.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
btn.setText("\t\t" + lbl + "\t\t\t ");
btn.setBackgroundResource(R.drawable.blue_button);
btn.setwidth(100);