我试图动态地将按钮添加到片段中,但它们没有显示出来。
这是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>
我没有收到任何错误信息,但是当我运行程序时,我看不到按钮。点击成功了,上面写着它的id是20。
1条答案
按热度按时间gpfsuwkq1#
将按钮添加到每次通过循环重新创建的线性布局中。