gpt4 book ai didi

android - 如何在 ListView 中显示与点击项目相关的数据? (点击监听器)

转载 作者:行者123 更新时间:2023-11-29 21:12:24 24 4
gpt4 key购买 nike

我有一个从 JSON 获取数据的 ListView 。到目前为止,我能够在 ListView 中显示数据。 (这里的数据是代理商列表)。现在我想在 ListView 中单击特定代理时打开一个新 Activity ,该 Activity 将显示代理详细信息,如姓名、电话、电子邮件等...

我很感激任何想法,因为我是 Android 新手。

我的代码:

public class MainActivity extends AppCompatActivity

{

private String jsonResult;
public String url = "http://111.111.111.1/androidapp/getjson.php";
ListView listView;
List<Map<String, String>> agents = new ArrayList<Map<String, String>>();

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
accessWebService();
}
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) {
Toast.makeText(getApplicationContext(), "error ..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}

@Override
protected void onPostExecute(String result)
{
ListDrwaer();
}
}

public void accessWebService() {
JsonReadTask task = new JsonReadTask();
task.execute(new String[]{url});
}

public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult.substring(jsonResult.indexOf("{"), jsonResult.lastIndexOf("}") + 1));
JSONArray jsonMainNode = jsonResponse.optJSONArray("agents");

final ArrayList<HashMap<String, String>> MyArrList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;

for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject c = jsonMainNode.getJSONObject(i);

map = new HashMap<String, String>();

map.put("AgtFirstName", c.getString("AgtFirstName"));
map.put("AgtLastName", c.getString("AgtLastName"));

MyArrList.add(map);

SimpleAdapter simpleAdapter;
simpleAdapter = new SimpleAdapter(MainActivity.this, MyArrList, R.layout.activity_column, new String[]{"AgtFirstName", "AgtLastName"}, new int[]{R.id.AgtFirstName , R.id.AgtLastName});

listView.setAdapter(simpleAdapter);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error parsing..." + e.toString(), Toast.LENGTH_LONG).show();
}
}



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



@Override
public boolean onOptionsItemSelected(MenuItem item) {

int id = item.getItemId();

if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,View view, int position, long id)
{
Intent i=new Intent(MainActivity.this,AgentDetails.class);
i.putExtra("position", map.get(position));
startActivity(i);

}
};

}

最佳答案

以下是您可以使用的两个选项。

1) 设置 OnItemClick,它将触发相应 ListView 条目中的任何组件(位置指示已选择哪个特定项目条目)(OnItemLongClick 也可以以类似的方式使用)。

2) 为 ListView 中的特定 View 设置 OnClick Listener。这允许对 ListView 条目中的不同元素/ View 执行特定操作。

例如,我有一个包含许多 TextView 的 ListView,我想对其中两个执行操作(标记为完成和删除),就像 Textview 是按钮一样。通过这些,我在 XML 中设置了 onClick。问题是您不知道哪个条目(即没有位置,解决方案使用 setTags)。我也有 OnItemClick。因此,单击其他位置可以执行其他选项/操作。

1(其他操作)的代码,其中 shoppingliSTLv 是 ListView(注意位置如何可用),这是在 onCreate 方法中:-

shoppinglistlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(view.getContext(), "ListView clicked", Toast.LENGTH_SHORT).show();
}
});

对于 2,我有:-

public void sledelete(View view) {
Integer tag = (Integer)view.getTag();
shoppinglistcsr.moveToPosition(tag);
shopperdb.setShopListEntryAsComplete(shoppinglistcsr.getLong(0));
shoppinglistcsr = shopperdb.getShoppingList();
currentsla.swapCursor(shoppinglistcsr);
}
public void slareorg(View view) {
shopperdb.reorgShopList();
shoppinglistcsr = shopperdb.getShoppingList();
currentsla.swapCursor(shoppinglistcsr);
}

连同(注意 onClick 会导致调用上述方法,setTag 是在适配器的 bindView 中完成的)。这是来自 ListView 条目的 XML,而不是 ListView 本身:-

        <TextView
android:id="@+id/shoppinglist_donebutton"
android:layout_width="@dimen/standard_dummy_size"
android:layout_height="@dimen/standard_subsubsubheading_height"
android:layout_weight="0.05"
android:singleLine="true"
android:text="@string/standarddonebutton"
android:gravity="center"
android:textSize="@dimen/standard_subsubsubheading_text_size"
android:textStyle="bold"
android:background="@color/colorNormalButton"
android:textColor="@color/colorNormalButtonText"
android:onClick="sledone"/>
<TextView
android:layout_width="@dimen/standard_dummy_size"
android:layout_height="match_parent"
android:layout_weight="0.005"/>
<TextView
android:id="@+id/shoppinglist_deletebutton"
android:layout_width="@dimen/standard_dummy_size"
android:layout_height="@dimen/standard_subsubsubheading_height"
android:layout_weight="0.05"
android:singleLine="true"
android:text="@string/standarddeletetext"
android:gravity="center"
android:textSize="@dimen/standard_subsubsubheading_text_size"
android:textStyle="bold"
android:background="@color/colorRequiredLabel"
android:textColor="@color/colorNormalButtonText"
android:onClick="sledelete"/>

与adpater的bindView一起(将标签设置为位置)注意donebtntv和deletebtntv持有各自的Textview id:-

// Set tags to enable onClick to determine the cursor position of the clicked entry
donebtntv.setTag(Integer.valueOf(pos));
deletebtntv.setTag(Integer.valueOf(pos));

最后,在 ListView 的 XML 根中我还有:-

android:descendantFocusability="afterDescendants"

(我不确定这是否是必需的,但是我确实得到了两种类型,上面的 1 和 2,用这个处理)

这可能过于复杂,但向您展示了一些选项。

下面是 OnItemClick 的更多示例代码,它们根据对话框选择启动其他 Activity 。这展示了如何通过 Intent extras 传递数据:-

// Click on an Aisle to update the Aisle or Stock the Aisle
aisleslistview = (ListView) findViewById(R.id.aalbclv01);
aisleslistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

AlertDialog.Builder okdialog = new AlertDialog.Builder(view.getContext());
okdialog.setTitle(getString(R.string.aislelistclicktitle));
okdialog.setMessage(getString(R.string.aislelistclicktext001));
okdialog.setCancelable(true);
okdialog.setPositiveButton(getString(R.string.standardedittext), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
resume_state = RESUMESTATE_AISLEUPDATE;
Intent intent = new Intent(findViewById(R.id.aalbclv01).getContext(), AisleAddActivity.class);
AislesCursorAdapter aisleadapter = (AislesCursorAdapter) ((ListView) findViewById(R.id.aalbclv01)).getAdapter();
intent.putExtra("Caller", THIS_ACTIVITY + "Update");
intent.putExtra("AisleID", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
intent.putExtra("AISLEID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
intent.putExtra("AisleName", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX));
intent.putExtra("AisleOrder", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX));
intent.putExtra("AisleShopRef", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
intent.putExtra("SHOPID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
startActivity(intent);
dialog.cancel();
}
});
okdialog.setNegativeButton(getString(R.string.standardstockaisletext), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
resume_state = RESUMESTATE_AISLESTOCK;
Intent intent = new Intent(findViewById(R.id.aalbclv01).getContext(), AddProductToShopActivity.class);
AislesCursorAdapter aisleadapter = (AislesCursorAdapter) ((ListView) findViewById(R.id.aalbclv01)).getAdapter();
intent.putExtra("Caller", THIS_ACTIVITY + "Stock");
intent.putExtra("AisleID", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
intent.putExtra("AISLEID", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_ID_INDEX));
intent.putExtra("AisleName", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_NAME_INDEX));
intent.putExtra("AisleOrder", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_ORDER_INDEX));
intent.putExtra("AisleShopRef", aisleadapter.getCursor().getString(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
intent.putExtra("AISLESHOPREF", aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
intent.putExtra("SHOPID",aisleadapter.getCursor().getLong(ShopperDBHelper.AISLES_COLUMN_SHOP_INDEX));
startActivity(intent);
dialog.cancel();
}
});
okdialog.setNeutralButton(getString(R.string.standardbacktext), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
resume_state = RESUMESTATE_NOTHING;
dialog.cancel();
}
});
okdialog.show();
}
});

注意!上面使用 SQlite/Cursors 作为列表源数据。但是,技术应该是相似的。

关于android - 如何在 ListView 中显示与点击项目相关的数据? (点击监听器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36254181/

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