我正在创建简单的列表视图。所有项目将成功列出。但
吐司不工作。代码的此链接我得到了错误。 Toast.makeText(this,"hello",fd.get(position),Toast.LENGTH_LONG).show();
完整代码
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = findViewById(R.id.List);
ArrayList<String> fd = new ArrayList<String>();
fd.add("roda");
fd.add("ghh");
fd.add("asfff");
fd.add("jll");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,fd);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{ Toast.makeText(MainActivity.this,"hello",fd.get(position),Toast.LENGTH_LONG).show();
}
});
}
}
答案 0 :(得分:2)
Toast.makeText(this,"hello"+fd.get(position),Toast.LENGTH_LONG).show();
尝试此代码
public class MainActivity extends AppCompatActivity {
ListView list;
private ArrayList<String> fd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = findViewById(R.id.List);
fd = new ArrayList<String>();
fd.add("roda");
fd.add("ghh");
fd.add("asfff");
fd.add("jll");
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,fd);
list.setAdapter(arrayAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{ Toast.makeText(MainActivity.this,"hello"+fd.get(position),Toast.LENGTH_LONG).show();
}
});
}
}
答案 1 :(得分:0)
在类级别声明您的ArrayList对象
var obj = {
num1: 1024,
num2: 1025,
num3: 1026,
num4: 1027
}
Object.keys(obj).forEach(e => obj[e] = "0x" + obj[e].toString(16))
console.log(JSON.stringify(obj))
在ListView list;
ArrayList<String> fd;
onCreate()
更改代码以显示如下吐司消息
fd = new ArrayList<String>();
答案 2 :(得分:-1)
首先,必须从fd
内部访问OnItemClickListener
。可以通过全局声明df或使df final
来实现。
第二,您不能在OnItemClickListener内使用this
,因为这需要替换行
Toast.makeText(this,"hello",fd.get(position),Toast.LENGTH_LONG).show();
与此:
Toast.makeText(MainActivity.this,"hello",fd.get(position),Toast.LENGTH_LONG).show();
并用您的活动名称替换MainActivity
。