Android:在按钮中添加不同的链接:onclick for listview中的每个按钮

时间:2016-10-21 18:20:01

标签: android listview

我从网站获取新闻文章的json,并在列表视图中显示文章标题+摘要。在每个摘要的下方,我想添加一个“阅读更多”'按钮将打开浏览器并访问网站上的特定文章。

但是,我如何设法让每个人阅读更多'按钮链接到特定的新闻文章而不是每个按钮到同一个一般网站?代码如下:

public class MainActivity extends AppCompatActivity {

private String TAG = MainActivity.class.getSimpleName();

private ProgressDialog pDialog;
private ListView lv;

// URL to get articles JSON
private static String url = "http://www.sample.com/json";

ArrayList<HashMap<String, String>> newsList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    newsList = new ArrayList<>();

    lv = (ListView) findViewById(R.id.list);

    new GetArticles().execute();
}

/**
 * Async task class to get json by making HTTP call
 */
private class GetArticles extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url);

        Log.e(TAG, "Response from url: " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                JSONArray articles = jsonObj.getJSONArray("articles");

                // looping through All Contacts
                for (int i = 0; i < articles.length(); i++) {
                    JSONObject c = articles.getJSONObject(i);

                    String title = c.getString("title");
                    String description = c.getString("description");
                    String weblink = c.getString("weblink");

                    // tmp hash map for single contact
                    HashMap<String, String> article = new HashMap<>();

                    // adding each child node to HashMap key => value
                    article.put("title", weblink);
                    article.put("description", weblink);
                    article.put("weblink", weblink);

                    // adding contact to contact list
                    newsList.add(article);
                }
            } catch (final JSONException e) {
                Log.e(TAG, "Json parsing error: " + e.getMessage());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Json parsing error: " + e.getMessage(),
                                Toast.LENGTH_LONG)
                                .show();
                    }
                });

            }
        } else {
            Log.e(TAG, "Couldn't get json from server.");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Couldn't get json from server. Check LogCat for possible errors!",
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, newsList,
                R.layout.list_item, new String[]{"title",
                "description"}, new int[]{R.id.title,
                R.id.description});

        lv.setAdapter(adapter);

    }

}


/** Called when the user clicks the read more button */
public void visitWebsite(View view) {
    Uri uri = Uri.parse("http://www.sample.com");
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}
}

下面的list_item.xml:

<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="@dimen/activity_horizontal_margin">

    <TextView
        android:id="@+id/title"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:paddingTop="6dip"
        android:textColor="@color/colorPrimaryDark"
        android:textSize="16sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/description"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="2dip"
        android:textColor="@color/colorAccent" />

    <Button
        android:id="@+id/weblink"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="read more"
        android:onClick="visitWebsite" />
</LinearLayout>

以下的activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    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="nl.ttvavanti.avanti.MainActivity">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</RelativeLayout>

2 个答案:

答案 0 :(得分:0)

您可以通过.setTag()getTag()方法将{/ 3}}作为TAG设置/获取不同的网址。

public void visitWebsite(View view) {
    Uri uri = Uri.parse(view.getTag().toString);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    startActivity(intent);
}

答案 1 :(得分:0)

我建议尝试使用ArrayAdapter而不是SimpleAdapter,并在数组适配器中使用OnclickListener而不是Button

就像在这个示例https://www.sitepoint.com/custom-data-layouts-with-your-own-android-arrayadapter/

中一样
相关问题