gpt4 book ai didi

Android 可点击 ListView

转载 作者:行者123 更新时间:2023-11-29 17:32:30 25 4
gpt4 key购买 nike

我有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com