gpt4 book ai didi

java - 查找 Include View 并更新 TextView

转载 作者:行者123 更新时间:2023-12-01 09:17:37 24 4
gpt4 key购买 nike

我有一个 fragment ,里面有

<include layout="@layout/card" android:id="@+id/card" />
<include layout="@layout/card" android:id="@+id/card1" />
<include layout="@layout/card" android:id="@+id/card2" />

我的卡片 xml 只是一张简单的卡片,如下所示

<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:gravity="left|center_vertical">

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="3"
android:padding="8dp"
android:text="Item Color"
android:textColor="#222"
android:textStyle="bold"
android:textSize="18dp"
android:gravity="center_vertical"/>

</LinearLayout>

我在我的java fragment 中尝试做的是加载第一张卡包含并更改其 TextView 文本这是我尝试过的,但它返回 null

View card1 =  getActivity().findViewById(R.id.card1);
TextView ct1 = (TextView) card1.findViewById(R.id.title);

那么我怎样才能实现我的目标或解决这个问题呢?感谢您的时间和帮助,非常感谢**** 更新 :这是整个 fragment

public class Home_Fragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {

//Inflate the layout for this fragment
ViewGroup card1 = (ViewGroup) getActivity().findViewById(R.id.card1);
TextView ct1 = (TextView) card1.findViewById(R.id.title);
ct1.setText("hey :P");

return inflater.inflate(
R.layout.home_fragment, container, false);

}
}

最佳答案

在 Fragment 的内容 View 上使用 .findViewById(R.id.card1); 而不是 getActivity()

public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View contentView = inflater.inflate(
R.layout.home_fragment, container, false);
//Inflate the layout for this fragment
ViewGroup card1 = (ViewGroup) contentView.findViewById(R.id.card1);
TextView ct1 = (TextView) card1.findViewById(R.id.title);
ct1.setText("hey :P");

return contentView;

}

关于java - 查找 Include View 并更新 TextView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40429386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com