无法在 android 微调器中添加提示
Unable to add hint in android spinner
我有一个 spinner
,它在我的 android application
中表现得像 dropdown
。我正在 android studio
开发应用程序。微调器从 api
获取数据。在 运行 时,它从 API
得到 usernames
并显示在 spinner
中。当应用 运行s 时,它显示 selected 用户的 username
和 ID
,如下图
所示
现在我想添加提示,所以我搜索了很多文章并找到了很多解决方案,我遵循了其中最简单的一个。更多理解请看下面的代码
try
{
JSONObject jobj = new JSONObject(jsonObject.toString());
// Locate the NodeList name
jsonArray = jobj.getJSONArray("users");
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
Users user = new Users();
user.setId(jsonObject.optString("Id"));
user.setName(jsonObject.optString("Name"));
users.add(user);
userList.add("Select a username");// i add this as a hint
userList.add(jsonObject.optString("Name"));
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
现在使用 onPostExecute() 方法
@Override
protected void onPostExecute(Void args)
{
// Locate the spinner in activity_main.xml
Spinner spinner = (Spinner)findViewById(R.id.spinner);
// Spinner adapter
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, userList));
// Spinner on item click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textViewResult = (TextView)findViewById(R.id.textView);
// Set the text followed by the position
// Set the text followed by the position
if(!users.get(position).getName().equals("Select a username")) {
textViewResult.setText(" " + users.get(position - 1).getName() + " " + users.get(position - 1).getId());
}else {
textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());
UserId = String.valueOf(users.get(position).getId());
progressDialog.dismiss();
_latitude.setText("");
_longitude.setText("");
Latitude = null;
Longitude = null;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
textViewResult.setText("");
}
});
}
当我 运行 应用程序崩溃时,出现以下错误
Process: com.example.accurat.myapp, PID: 30382
java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at com.example.accurat.myapp.MainActivity$DownloadJSON.onItemSelected(MainActivity.java:494)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:931)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:920)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:890)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5491)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
此错误发生在 textViewResult.setText(" " + users.get(position - 1).getName() + " " + users.get(position - 1).getId());
点
更新 1
根据 Junaid Hafeez
的回答,我做了以下
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
Users user = new Users();
user.setId(jsonObject.optString("Id"));
user.setName(jsonObject.optString("Name"));
users.add(user);
userList.add(jsonObject.optString("Name"));
}
userList.add(0, "Select a username"); // after for loop ended i add `select a username` at `0` index
之后在 postExecute()
方法中我做了以下
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textViewResult = (TextView)findViewById(R.id.textView);
// Set the text followed by the position
// Set the text followed by the position
if(position>0)
{
textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());
UserId = String.valueOf(users.get(position).getId());
_latitude.setText("");
_longitude.setText("");
Latitude = null;
Longitude = null;
}
else {
}
progressDialog.dismiss();
}
我得到的结果低于
它确实向我显示了提示,但是当我 select 任何用户名时,它会向我显示下一个用户名的 name
和 id
,如下图
我一直坚持,找不到任何解决方案
非常感谢任何帮助。
可能您正在做的是,您正在单击微调器的第一项,其中 position = 0
并在 setText
中执行 position - 1
这使得索引 -1
实际上不存在并且崩溃了。
其次你这样做
userList.add("Select a username");// i add this as a hint
在你的循环中,它在每次迭代中添加新项目。
你需要做的是
获得完整的数据列表后,
像这样在它的 0 索引上添加提示
userList.add(0, "Select a username");
在你的 onClick 中,检查天气 position > 0
然后做你的工作,否则当用户点击提示时忽略。
你好使用下面的库作为提示微调器
package com.keshav.spinnerhintexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btn_submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
btn_submit = (Button) findViewById(R.id.btn_submit);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (position == getCount()) {
((TextView)v.findViewById(android.R.id.text1)).setText("");
((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
}
return v;
}
@Override
public int getCount() {
return super.getCount()-1; // you dont display last item. It is used as hint.
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Daily");
adapter.add("Two Days");
adapter.add("Weekly");
adapter.add("Monthly");
adapter.add("Three Months");
adapter.add("Select a Item"); //This is the text that will be displayed as hint.
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount()); //set the hint the default selection so it appears on launch.
// spinner.setOnItemSelectedListener(this);
btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String item=spinner.getSelectedItem().toString();
Log.e("keshav","selectedItem is ->" + item);
if(spinner.getSelectedItem().toString().equals("Select a Item")){
Toast.makeText(MainActivity.this,"Please Select an Item",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this,"selected Item is -> "+item,Toast.LENGTH_LONG).show();
}
}
});
}
}
-------------------Xml File ----------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.keshav.spinnerhintexample.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="40dp"
/>
<Button
android:id="@+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:background="@color/colorPrimaryDark"
android:text="Submit"
android:textColor="#FFFFFF"
/>
</RelativeLayout>
我有一个 spinner
,它在我的 android application
中表现得像 dropdown
。我正在 android studio
开发应用程序。微调器从 api
获取数据。在 运行 时,它从 API
得到 usernames
并显示在 spinner
中。当应用 运行s 时,它显示 selected 用户的 username
和 ID
,如下图
现在我想添加提示,所以我搜索了很多文章并找到了很多解决方案,我遵循了其中最简单的一个。更多理解请看下面的代码
try
{
JSONObject jobj = new JSONObject(jsonObject.toString());
// Locate the NodeList name
jsonArray = jobj.getJSONArray("users");
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
Users user = new Users();
user.setId(jsonObject.optString("Id"));
user.setName(jsonObject.optString("Name"));
users.add(user);
userList.add("Select a username");// i add this as a hint
userList.add(jsonObject.optString("Name"));
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
现在使用 onPostExecute() 方法
@Override
protected void onPostExecute(Void args)
{
// Locate the spinner in activity_main.xml
Spinner spinner = (Spinner)findViewById(R.id.spinner);
// Spinner adapter
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, userList));
// Spinner on item click listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textViewResult = (TextView)findViewById(R.id.textView);
// Set the text followed by the position
// Set the text followed by the position
if(!users.get(position).getName().equals("Select a username")) {
textViewResult.setText(" " + users.get(position - 1).getName() + " " + users.get(position - 1).getId());
}else {
textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());
UserId = String.valueOf(users.get(position).getId());
progressDialog.dismiss();
_latitude.setText("");
_longitude.setText("");
Latitude = null;
Longitude = null;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
textViewResult.setText("");
}
});
}
当我 运行 应用程序崩溃时,出现以下错误
Process: com.example.accurat.myapp, PID: 30382
java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
at java.util.ArrayList.get(ArrayList.java:310)
at com.example.accurat.myapp.MainActivity$DownloadJSON.onItemSelected(MainActivity.java:494)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:931)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:920)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:890)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5491)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
此错误发生在 textViewResult.setText(" " + users.get(position - 1).getName() + " " + users.get(position - 1).getId());
更新 1
根据 Junaid Hafeez
的回答,我做了以下
for(int i=0; i<jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
Users user = new Users();
user.setId(jsonObject.optString("Id"));
user.setName(jsonObject.optString("Name"));
users.add(user);
userList.add(jsonObject.optString("Name"));
}
userList.add(0, "Select a username"); // after for loop ended i add `select a username` at `0` index
之后在 postExecute()
方法中我做了以下
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textViewResult = (TextView)findViewById(R.id.textView);
// Set the text followed by the position
// Set the text followed by the position
if(position>0)
{
textViewResult.setText("Hi " + users.get(position).getName() + " your ID is " + users.get(position).getId());
UserId = String.valueOf(users.get(position).getId());
_latitude.setText("");
_longitude.setText("");
Latitude = null;
Longitude = null;
}
else {
}
progressDialog.dismiss();
}
我得到的结果低于
它确实向我显示了提示,但是当我 select 任何用户名时,它会向我显示下一个用户名的 name
和 id
,如下图
我一直坚持,找不到任何解决方案
非常感谢任何帮助。
可能您正在做的是,您正在单击微调器的第一项,其中 position = 0
并在 setText
中执行 position - 1
这使得索引 -1
实际上不存在并且崩溃了。
其次你这样做
userList.add("Select a username");// i add this as a hint
在你的循环中,它在每次迭代中添加新项目。 你需要做的是
获得完整的数据列表后, 像这样在它的 0 索引上添加提示
userList.add(0, "Select a username");
在你的 onClick 中,检查天气 position > 0
然后做你的工作,否则当用户点击提示时忽略。
你好使用下面的库作为提示微调器
package com.keshav.spinnerhintexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button btn_submit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Spinner spinner = (Spinner) findViewById(R.id.spinner);
btn_submit = (Button) findViewById(R.id.btn_submit);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
if (position == getCount()) {
((TextView)v.findViewById(android.R.id.text1)).setText("");
((TextView)v.findViewById(android.R.id.text1)).setHint(getItem(getCount())); //"Hint to be displayed"
}
return v;
}
@Override
public int getCount() {
return super.getCount()-1; // you dont display last item. It is used as hint.
}
};
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.add("Daily");
adapter.add("Two Days");
adapter.add("Weekly");
adapter.add("Monthly");
adapter.add("Three Months");
adapter.add("Select a Item"); //This is the text that will be displayed as hint.
spinner.setAdapter(adapter);
spinner.setSelection(adapter.getCount()); //set the hint the default selection so it appears on launch.
// spinner.setOnItemSelectedListener(this);
btn_submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String item=spinner.getSelectedItem().toString();
Log.e("keshav","selectedItem is ->" + item);
if(spinner.getSelectedItem().toString().equals("Select a Item")){
Toast.makeText(MainActivity.this,"Please Select an Item",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(MainActivity.this,"selected Item is -> "+item,Toast.LENGTH_LONG).show();
}
}
});
}
}
-------------------Xml File ----------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.keshav.spinnerhintexample.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<Spinner
android:id="@+id/spinner"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_marginTop="40dp"
/>
<Button
android:id="@+id/btn_submit"
android:layout_width="match_parent"
android:layout_height="45dp"
android:layout_alignParentBottom="true"
android:layout_margin="10dp"
android:background="@color/colorPrimaryDark"
android:text="Submit"
android:textColor="#FFFFFF"
/>
</RelativeLayout>