【发布时间】:2021-10-02 18:34:10
【问题描述】:
我正在尝试向片段动态添加按钮,但它们没有显示。
这是 listCharacter.java:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_list_character, container, false);
context = view.getContext();
for (int i = 1; i <= 20; i++) {
LinearLayout layout = new LinearLayout(context);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button firstBtn = new Button(this.context);
firstBtn.setId(i);
final int id_ = firstBtn.getId();
/**
* The text is not updated(?)
*/
firstBtn.setText("button " + id_);
/**
* it does not add 20 button, might be on top of each other
*/
layout.addView(firstBtn, params);
firstBtn = view.findViewById(R.id.characterNameBtn);
firstBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
Navigation.findNavController(view).navigate(R.id.action_listCharacter_to_loadCharacter);
}
});
}
return view;
}
这是fragment_list_character.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/background"
tools:context=".listCharacter"
android:orientation="vertical">
<LinearLayout
android:id="@+id/list_character_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<Button
android:id="@+id/characterNameBtn"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#66000000"
android:fontFamily="@font/main"
android:gravity="center"
android:padding="5dp"
android:text=""
android:textColor="#fff"
android:textSize="40sp"
/>
</LinearLayout>
</LinearLayout>
我没有收到任何错误消息 atm,但我在运行程序时看不到按钮。 点击有效,它说它的 id 为 20。
【问题讨论】:
-
您正在尝试显示一些
listCharacter列表并在按钮单击时打开特定字符屏幕loadCharacter。不需要像这样在运行时将按钮添加到线性布局中。您可以使用简单的RecyclerView 来根据需要扩充任意数量的字符;不仅是您的示例中的 20 个。然后为 ViewHolder 对象中的按钮注册一个点击监听器;根据位置,您可以将必要的信息传输到loadCharacter屏幕。 -
谢谢!这实际上对我有用!对于那些也尝试重新创建的人,回收查看器对我不起作用,所以我使用了这个代码“
标签: java android android-layout android-fragments