在这种情况下,如何以编程方式将按钮膨胀为线性布局?



我的任务是生成几个具有固定宽度和高度的按钮。我决定将这些按钮存储在某个 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并将该按钮膨胀到此视图。之后,我通过其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) ;
}
}

一切都发生在碎片中。generatePlaces方法在onViewCreated之后调用。如何解决我的问题?

可能由于缺少ButtonID 而遇到问题

<?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"/>

更新:

当你做通货膨胀时,你已经得到了你的按钮视图,不需要做findViewById。

总的来说,我不认为在你的情况下夸大观点是一个好方法。最好创建按钮:

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);
}

我认为这是因为您更改了按钮的id,在下一次迭代中,您会得到一个空指针异常。我会说完全以编程方式创建按钮视图,而不是从 xml 创建按钮视图,然后将其附加到父视图。或者查看类似列表视图的东西。

我会说采用您之前的方法,并参考此问题以转换为 DP。

最新更新