Android 可点击 ListView

标签 android json listview onclick clickable

我有一个 android 代码,它从 php 文件中获取一些 json 格式的数据, 我使用这些 json 成功创建了一个 ListView ,现在我想创建第二个 Activity 以在我单击这些项目时显示产品详细信息。

代码如下:

public class MainActivity extends Activity {
    private String jsonResult;
    private String url = "xxxx/get_all_products.php";
    private ListView listView;

    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_FOUND = "found";
    private static final String TAG_DESCRIPTION = "description";

    ArrayList<HashMap<String, String>> productList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView1);
        productList = new ArrayList<HashMap<String, String>>();



        accessWebService();


        }




    // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            ListDrwaer();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[]{url});
    }

    // build hash set for list view
    public void ListDrwaer() {
        List<Map<String, String>> productList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("products");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("name");
                String price = jsonChildNode.optString("price");
                    String found = jsonChildNode.optString("found");
                //    String outPut = name + "-" + number;
           //     String outPut = name + "-" + price + "-" + found;
           //     productList.add(createProduct("products", outPut));
                HashMap<String, String> product = new HashMap<String, String>();

                product.put(TAG_NAME, name);
                product.put(TAG_FOUND, found);
                product.put(TAG_PRICE, price);

               productList.add(product);
            }
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                    Toast.LENGTH_SHORT).show();
        }




        SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
                R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
                TAG_FOUND }, new int[] { R.id.name,
                R.id.price, R.id.found });
        listView.setAdapter(simpleAdapter);

        }

        }

还有两个xml布局文件。 我读了很多关于 setOnItemClickListener 的例子,但没有成功...... 例如尝试这个没有成功:

  listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String selval = ((TextView) view).getText().toString();


                Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
                intnt.putExtra("selval ", selval);


            }

这里是错误:

FATAL EXCEPTION: main
    java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView
            at sig.example.com.sig00.MainActivity$1.onItemClick(MainActivity.java:59)

这是 xml 文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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=".MainActivity" >
    <!-- Name Label -->
    <!--   android:id="@+id/listView1" -->
    <ListView
        android:id="@+id/listView1"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_alignParentTop="true"
       android:layout_centerHorizontal="true"
       android:layout_marginTop="14dp">
   </ListView>

list_item.xml 是

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="10dp"
    android:paddingLeft="10dp"
    android:paddingRight="10dp" >

    <!-- Name Label -->

    <TextView
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="#43bd00"
        android:textSize="16sp"
        android:textStyle="bold"
        android:gravity="center"/>

    <!-- Email label -->
    <TextView
        android:id="@+id/price"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="#acacac" />

    <!-- Mobile number label -->
    <TextView
        android:id="@+id/found"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:textColor="#5d5d5d"
        android:textStyle="bold" />



</LinearLayout>

最佳答案

将您的代码从 setOnItemClickListener() 替换为此代码:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
 public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
     String selval = listview.getItemAtPosition(position).getText().toString();
     // Also I've found a solution on SO that a guy solved this problem doing soemthing like this : 
     // TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
     // String keyword = txt.getText().toString();
     Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
     intnt.putExtra("selval ", selval);

编辑

你的错误是你在你的 Intent 中放置了额外的“selval”,带有BLANK SPACE所以如果你在下一个 Activity 中你这样做:

Class SingleListItem extends Activity{ 
@Override
public void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  this.setContentView(R.layout.productdetails); 
  TextView txtProduct = (TextView) findViewById(R.id.product_label); 
  Intent i = getIntent(); // getting attached intent data 
  String selval = i.getStringExtra("selval"); // displaying selected product name txtProduct.setText(selval); 
}

它永远不会返回您的 selval 字符串,因为您要求的不是来自 “selval” 的“sevlal”。

只需删除不必要的空间即可:)

关于Android 可点击 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32229025/

相关文章:

java - android套接字连接后卡住

android - 开启第二个 Activity 失败

python - 将 json 对象列表展平到表中,并为 Databricks 中的每个对象提供列

android - 为什么 LogCat 不显示完整消息?

json - 如何在 mongodb 中展平子文档

php - 如何将秒表结果(数组)推送到第一个表结果(数组)

加载数据库的 Android ListView 非常慢

android - 动态更改 ListView 中所有项目的文本颜色

Android 布局 - ListView 占用太多空间

java - 更改 AdView 位置时出现 ClassCastException