查找包含视图并更新TextView

时间:2016-11-04 18:17:43

标签: java android android-fragments

我有一个片段,里面有我的

<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片段中尝试做的是加载第一张卡片包含并选择其文本视图文本 这是我尝试但它返回null

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

那么我如何实现目标或解决这个问题呢? 感谢您的时间和帮助,感谢您 ****更新: 继承人整个片段

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

   }
}

1 个答案:

答案 0 :(得分:1)

在片段的内容视图上使用package Pali; import java.util.Scanner; /** * Created by alexa on 11/4/2016. */ public class Palindromes { public static void main(String[] args) { String msg; Scanner scan = new Scanner(System.in); System.out.print("Enter a string: "); msg = scan.nextLine(); System.out.print("\nThe string backwards: "); printBackwards(msg); System.out.println(); } public static String printBackwards(String s) { if (s.length() == 0) return s; return printBackwards(s.substring(1)) + s.charAt(0); } } 而不是.findViewById(R.id.card1);

getActivity()

}