我已经仔细研究了许多类似的问题,但我无法找到我想要的答案。我几乎是自学成才,所以我为这个问题道歉。基本上我试图访问我的数组中的字符串ID并将其转换为可读的字符串,以便我可以将其发送到谷歌地图,以便用户可以在那里导航。这是我得到的最接近的。
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class FoodFragment extends Fragment {
public FoodFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.word_list, container, false);
final ArrayList<Location> places = new ArrayList<>();
places.add(new Location(R.string.food1, R.string.desc1, R.drawable.tapass));
places.add(new Location(R.string.food2, R.string.desc2, R.drawable.baguette));
places.add(new Location(R.string.food3, R.string.desc3, R.drawable.sushi));
places.add(new Location(R.string.food4, R.string.desc4, R.drawable.burger));
places.add(new Location(R.string.food5, R.string.desc5, R.drawable.meat));
places.add(new Location(R.string.food6, R.string.desc6, R.drawable.pizza));
final Location here = places.get(0);
final int address = here.getName();
MyAdapter adapter = new MyAdapter(getActivity(), places);
final ListView listView = (ListView) rootView.findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("google.navigation:q=" + address));
startActivity(intent);
}
});
return rootView;
}
}
getName来自我的Location类。我意识到它返回一个int(这样我可以将string.xml中的字符串id放入数组中)但是如何让它返回实际的字符串值呢?
public class Location {
private int mName;
private int mDescription;
private int mImage;
public Location (int name, int description, int image){
mName = name;
mDescription = description;
mImage = image;
}
public int getName(){
return mName;
}
public int getDescription(){
return mDescription;
}
public int getImage(){
return mImage;
}
}
我再次为noob问题道歉,非常感谢任何帮助。
答案 0 :(得分:0)
您应该将Location类更改为此类
public class Location {
private int mName;
private int mDescription;
private int mImage;
private Context mContext;
public Location (int name, int description, int image, Context context){
mName = name;
mDescription = description;
mImage = image;
mContext = context;
}
public String getName() {
return mContext.getString(mName)
}
public int getDescription(){
return mDescription;
}
public int getImage(){
return mImage;
}
}
然后您可以像这样创建位置实例
places.add(new Location(R.string.food1, R.string.desc1, R.drawable.tapass, getActivity()));
答案 1 :(得分:0)
此处address
是id
的资源string.xml
您可以使用
address
id的值
String value = getString(address);