2016-11-04 32 views
0

我有它裏面,我有查找包含視圖和更新的TextView

<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片段正在加載第一張卡片包括和chnage其文本查看文本 這是我試過但它返回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

使用.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; 

}

+0

I did and same thing 11-04 22:03:28.781 E/AndroidRuntime(30131):java.lang.RuntimeException:無法啓動活動ComponentInfo {mr.aide.theme.engine/mr.aide.theme.engine。 ThemeActivity}:jav a.lang.NullPointerException:試圖調用虛擬方法'android.view.View android.view.ViewGroup.findViewById(int)'null對象引用 – NikanDalvand

+0

@NikanDalvand我已更新我的答案 –

+0

繼承人代碼我試過ViewGroup card1 = (ViewGroup)getActivity()。findViewById(R.id.card1); – NikanDalvand