findViewById在片段内搜索ImageView时返回null,但不是TextView。
这是我的代码:
fragment.xml之:
<android.support.design.widget.CoordinatorLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.herecomesthefragmentname">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/card_1"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/txt_1"
android:textAppearance="@android:style/TextAppearance.Medium" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/2_card"
app:cardUseCompatPadding="true"
app:cardBackgroundColor="@android:color/white">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mr_layout">
<ImageView
android:id="@+id/2_imag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@drawable/img_1"
android:scaleType="fitStart"
android:adjustViewBounds="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txt_2"
android:textAppearance="@style/TextAppearance.AppCompat.Large.Inverse"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
<!-- here goes another cardview -->
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
fragment.java(不是全部):
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment, container, false);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//Get Views
txt_container = (TextView) view.findViewById(R.id.txt_2);
img_view = (ImageView) view.findViewById(R.id.2_imag);
}
奇怪的是找到了txt_2
视图,但找不到2_imag
视图。
我尝试过重命名,但它什么也没做。此外,我注意到我无法找到RelativeLayout和CardView包含。
更新:我似乎无法找到主协调员布局
答案 0 :(得分:0)
解决了,正在加载fragment-v21.xml文件而不是fragment.xml。
v21有不同的代码。