Android:单击时在列表视图中显示项目的详细信息

时间:2015-07-14 11:37:19

标签: android object android-listview displayobject

我正在开发一个Android项目,我正在为用户显示项目列表。现在,我想要做的是当用户点击该项目时,我想要该项目的ID,以便我可以通过网络调用对象详细信息并将其显示在另一个活动中。现在的问题是,显示的对象只包含名称。我无法找到方法,设置隐藏的项目的ID,然后我可以在用户点击并执行后续任务时检索该ID。有没有办法将id设置在某个用户无法看到并可以使用的地方。

以下是代码:

public class RestaurantList extends Activity {

    String restaurantList = "http://192.168.178.60:8080/restaurant/listing";

    private ResponseEntity<RestRestaurant[]> responseEntity;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        ListView listView = (ListView) findViewById(R.id.restRestaurantList);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.restos);
       RestTemplate restTemplate = StaticRestTemplate.getRest();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.add("Cookie", "JSESSIONID=" + StaticRestTemplate.jsessionid);
                requestHeaders.setAccept(Collections.singletonList(new MediaType("application", "json")));
                HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                responseEntity= restTemplate.exchange(restaurantList, HttpMethod.GET,requestEntity,RestRestaurant[].class);
            }
        });
        thread.start();
        ProgressDialog progress = new ProgressDialog(this);
        progress.setTitle("Loading");
        progress.setMessage("Wait while loading...");
        while (thread.getState()!=Thread.State.TERMINATED){
            progress.show();
        }
        progress.dismiss();

        RestRestaurant[] restRestaurantList = responseEntity.getBody();
        ArrayList<String> list = new ArrayList<>();

        for (RestRestaurant restRestaurant1 : restRestaurantList){
            Log.d("RestRestaurant name", restRestaurant1.getRestaurantName());
            list.add(restRestaurant1.getRestaurantName());
        }
// I am getting error at below line, saying StableArrayAdapter cannot be applied to RestRestaurant. 
        final StableArrayAdapter adapter = new StableArrayAdapter(this,
                android.R.layout.simple_list_item_1, list);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, final View view,
                                    int position, long id) {
                final String item = list.get(position);
                view.animate().setDuration(2000).alpha(0)
                        .withEndAction(new Runnable() {
                            @Override
                            public void run() {



                            }
                        });
            }

        });
    }

    private class StableArrayAdapter extends ArrayAdapter<RestRestaurant> {

        HashMap<Integer, Integer> mIdMap = new HashMap<Integer, Integer>();

        public StableArrayAdapter(Context context, int textViewResourceId,
                                  List<RestRestaurant> objects) {
            super(context, textViewResourceId, objects);
            for (int i = 0; i < objects.size(); ++i) {
                mIdMap.put(objects.get(0).getRestaurantId(), i);
            }
        }

        @Override
        public long getItemId(int position) {
            RestRestaurant item = getItem(position);
            return mIdMap.get(item);
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

    }

    @Override
    public void onBackPressed()
    {
        Intent intent = new Intent(RestaurantList.this, Login.class);
        StaticRestTemplate.jsessionid = null;
        StaticRestTemplate.replyString = null;
        startActivity(intent);
        finish();
    }
}

xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <ListView
            android:layout_width="match_parent"
            android:layout_height="457dp"
            android:id="@+id/restRestaurantList" android:layout_gravity="center_horizontal"
            android:layout_marginTop="20dp"/>

</LinearLayout>

请让我知道我做错了什么。

5 个答案:

答案 0 :(得分:0)

您可以在视图中设置整个对象并获取该对象(在您的情况下:RestRestaurant)

1. in your activity, implement list - onclick listener:

listview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

}
    });
    在适配器中
  1. ,将标记添加到getView()中的每个项目:

    view.setTag(RestRestaurant的对象);

  2. 内部活动,在onClick中,当您获得视图时: 你只需要打电话:

    RestRestaurant rest =((RestRestaurant)v.getTag());

  3. 所以,在这里你选择了项目。

答案 1 :(得分:0)

创建一个bean,其中一个项目存储id和第二个字符串,当单击列表时获取位置并从该位置获取id并执行您想要对该id执行的操作。

class Bean{

int id,
String name;

getter setter;

}

Activity{
List<Bean> beanList

ListView.setOnitemClicklistener()
{

onclick(position)


{
beanList.get(position).getId;
do whatever you want to do now

}

}


}

答案 2 :(得分:0)

我发现最简单的方法是创建一个自定义Object,其中包含您需要的ID和名称,并overridetoString() method该对象的return class BasicForm(Form): some_select = RadioField("something", choices=[('first', 'first_choice'), ('second', 'second_choice')]) 无论你想在列表中显示什么,所以在你的情况下,名称。

答案 3 :(得分:0)

我们的想法是继承ArrayAdapter,并在新类中保存ID和值之间的映射。

答案 4 :(得分:0)

看看这个。

这是mainActivity:

public class MainActivity extends ActionBarActivity
{

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ArrayList<YourClass> list = new ArrayList<YourClass>();
    YourClass yc = new YourClass();
    yc.name = "aaa";
    list.add(yc);
    yc = new YourClass();
    yc.name = "bbb";
    list.add(yc);
    yc = new YourClass();
    yc.name = "ccc";
    list.add(yc);
    ListView mList = (ListView) findViewById(R.id.restRestaurantList);
    YourListAdapter adapter1 = new YourListAdapter(this, android.R.layout.simple_list_item_1, list);
    mList.setAdapter(adapter1);
}

public class YourListAdapter extends ArrayAdapter<YourClass>
{

    ArrayList<YourClass> _List = null;

    public YourListAdapter(Context context, int typ, ArrayList<YourClass> List)
    {
        super(context, typ, List);
        // TODO Auto-generated constructor stub
        mContext = context;
        _List = List;
    }

    private final Context mContext;

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        TextView rowView = (TextView)inflater.inflate(android.R.layout.simple_list_item_1, parent, false);
        rowView.setText(_List.get(position).toString());
        return rowView;
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

你的班级:

public class YourClass
{
 public Long id;
 public String name;

 @Override
 public String toString()
 {
     return name;
 }
}

布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

<ListView
        android:layout_width="match_parent"
        android:layout_height="457dp"
        android:id="@+id/restRestaurantList" 
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"/>
</LinearLayout>

复制粘贴,它必须工作!! PS。抱歉延迟