我无法理解为什么我在这里收到错误。错误是 spinner1 无法解决。请快速帮助我。我是 java 和 android 开发新手,所以请相应地解释一下。
这是我的java代码
package com.example.dailyexpenses;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.ViewGroup;
public class GamesFragment extends Fragment {
String[] Languages = { "Select a Language", "C# Language", "HTML Language",
"XML Language", "PHP Language" };
// Declaring the Integer Array with resourse Id's of Images for the Spinners
Integer[] images = { 0, R.drawable.icon, R.drawable.petrol,
R.drawable.books, R.drawable.recharge};
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_games, container, false);
Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);
return rootView;
}
}
这是fragment_games.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:text="choose from the categories below"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:drawSelectorOnTop="true"
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/select">
</Spinner>
</RelativeLayout>
最佳答案
您需要调用
rootView.findViewById
因为 android 还不知道在哪里搜索。
更多说明:
可能(不是判断 ofc)您熟悉在 Activity 的 onCreate
方法中调用 findViewById
,但在此之前您确实调用过 setContentView
.通过setContentView
设置内容后,当您调用findViewById
时,android知道在哪里搜索id。这是当您使用 Activity 时的情况。另一方面,对于 fragment 来说,情况就不同了。您不会通过 setContentView
设置内容,而是必须准备一个 View 并在 onCreateView
上返回它,然后让 android 根据需要设置内容。请注意,在上面调用 findViewById
的行中,您还没有返回 View ,因此当您调用 findViewById
时,Android 不知道在哪里搜索。因此,您必须不在未设置的内容上进行搜索,而是在您即将返回的 rootView
上进行搜索。所以上面的代码是这个描述清楚的问题的解决方案。
关于java - spinner1 无法解析或不是字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964811/