我的任务是生成几个具有固定宽度和高度的按钮。我决定将这些按钮存储在一些 ArrayList 中以备将来使用。我是这样做的:
for(int i = 1 ; i<=n; i++)
{
Button place = new Button(this.context) ;
place.setTextColor(ContextCompat.getColor
(this.context,R.color.background_color));
place.setTypeface(typefaceForPlaces);
place.setId(i+0);
place.setBackgroundResource(R.drawable.real_place_background);
place.setLayoutParams(new
LinearLayout.LayoutParams(65,65));
places.add(place);
}
但是问题来了
place.setLayoutParams(newLinearLayout.LayoutParams(65,65));
这里,宽度和高度以像素为单位设置。但我需要 dp
。我知道代码
将 dp 转换为像素,但我认为这不是好的解决方案。现在,我想创建一些布局并将按钮的形状存储在那里。这是我为这个名为 place_button.xml
的布局:
<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/real_place_background"
android:textColor="#202020">
</Button>
然后我创建了一些 View
并将那个按钮膨胀到这个 View 。之后,我通过它的id得到上面的按钮并将它保存到另一个按钮,因为我需要很多这样的按钮。然后我需要更改新按钮的 ID。但是我收到以下错误:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.incubic.abay.clasico/com.incubic.abay.clasico.GameActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setId(int)' on a null object reference
下面是我的代码:
private void generatePlaces() {
View place_view = LayoutInflater.from(getContext()).inflate(R.layout.place_button,null);
for(int i = 1 ; i<=n; i++)
{
Button place = (Button)place_view.findViewById(R.id.button_id);
place.setId(i+0);
place.setTypeface(typefaceForPlaces);
places.add(place) ;
}
}
一切都发生在 Fragment 中。 generatePlaces
方法在 onViewCreated
之后调用。如何解决我的问题?
最佳答案
可能是因为缺少Button
id
<?xml version="1.0" encoding="utf-8"?>
<Button
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/real_place_background"
android:textColor="#202020"/>
更新:
当您执行 inflation 时,您已经获得了 Button View ,无需执行 findViewById。
总的来说,我认为在您的案例中夸大 View 不是一个好方法。更好地创建按钮:
private void generatePlaces()
{
for (int i = 1; i <= n; i++)
{
Button place = new Button(this.context);
place.setTextColor(ContextCompat.getColor(this.context, R.color.background_color));
place.setTypeface(typefaceForPlaces);
place.setId(i + 0);
place.setBackgroundResource(R.drawable.real_place_background);
place.setLayoutParams(new LinearLayout.LayoutParams(dpToPx(50), dpToPx(50)));
places.add(place);
}
}
private int dpToPx(int dp)
{
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
关于android - 在这种情况下,如何以编程方式将 Button 膨胀为 LinearLayout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45307196/