Android ListView 项目点击不会转到正确的屏幕

标签 android jsoup

我制作了一个应用程序,其中列出了我使用 jsoup 从 Html 页面解析的一些链接。

该列表显示链接的标题和应该有链接的箭头。但是当我选择其中的任何一项时,我只会得到最后一个链接。

这是我的 Controller :

public class Controller extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_view);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setTitle("");
        toolbar.setSubtitle("");
        linkList = new ArrayList<>();
        http = this.getString(R.string.http);
        url = this.getString(R.string.path1);
        lv = (ListView) findViewById(R.id.list);
        new GetLinks().execute();
    }

    private class GetLinks extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            Document doc;
            Elements links;

            try {
                doc = Jsoup.connect(url).get();
                links = doc.getElementsByClass("processlink");
                linkList = ParseHTML(links);
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            ListAdapter adapter = new SimpleAdapter(
                    Controller.this, linkList,
                    R.layout.list_item, new String[]{TITLE, LINK},
                    new int[]{R.id.title});
            //Log.i(TAG, "onPostExecute: "+ getString(R.id.link));
            lv.setAdapter(adapter);
        }
    }

    private ArrayList<HashMap<String, String>> ParseHTML(Elements links) throws IOException {

        if (links != null) {

            ArrayList<HashMap<String, String>> linkList = new ArrayList<>();

            for (Element link : links) {
                final String linkhref = http + link.select("a").attr("href");
                String linktext = link.text();

                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent,
                                            View view, int position, long id) {
                        Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                                Uri.parse(linkhref));
                        startActivity(browserIntent);
                    }
                });

                HashMap<String, String> student = new HashMap<>();
                student.put(TITLE, linktext);
                student.put(LINK, linkhref);

                linkList.add(student);
            }

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

这是 main_view.xml

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView2" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:textSize="20sp"
    android:textStyle="bold"
    android:textColor="@color/colorPrimary"
    android:text="@string/app_name"
    android:gravity="center"
    android:id="@+id/textView2"
    android:layout_below="@+id/toolbar"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

最后但同样重要的是,list_item.xml

<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"
    android:text="Title"
    android:layout_toLeftOf="@+id/link"
    android:layout_toStartOf="@+id/link" />

<ImageView
    android:id="@+id/link"
    android:layout_width="35dp"
    android:layout_height="wrap_content"
    android:gravity="end"
    android:src="@drawable/arrow"
    android:autoLink="web"
    android:padding="1dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:layout_alignBottom="@+id/title" />

如果我记录标题和链接,我会得到所有链接和标题,但不在应用程序中。

所以我的问题是如何让链接作为列表工作,而不仅仅是最后一个链接?

最佳答案

我猜 linkList 已经在全局中声明了。所以你可以接受这个。

无论如何,我很乐意建议您对代码进行一些修改。您可以在 onCreate 函数中完全初始化您的 ListView。将您的 Adapter 声明为全局变量。

您也可以考虑在 onCreate 函数中设置 ListView 项目的 onClickListener

// Declare the adapter globally.
private ListAdapter adapter;

// Declare the linkList as an ArrayList of Student object
private ArrayList<Student> linkList;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_view);
    // ... Setup toolbar
    // ... Setup http and url string

    // Setup ListView
    linkList = new ArrayList<Student>();
    lv = (ListView) findViewById(R.id.list);

    // Initialize the adapter
    adapter = new SimpleAdapter(
                Controller.this, linkList,
                R.layout.list_item, new String[]{TITLE, LINK},
                new int[]{R.id.title});        

    // Set the adapter here
    lv.setAdapter(adapter); 

    // Setup the ListView item click
    setupListViewItemClick();

    // Now execute the AsyncTask
    new GetLinks().execute();
}

这是 setupListViewItemClick 函数,它可能看起来像这样。

private void setupListViewItemClick() {
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent,
                View view, int position, long id) {

            // Get the student by the position of the adapter.
            Student student = linkList.get(position);
            String linkhref = student.getLink();

            Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(linkhref));
            startActivity(browserIntent);
        }
    });
}

因此,您需要修改您的ParseHTML 函数。

private ArrayList<Student> ParseHTML(Elements links) throws IOException {

    if (links != null) {
    // Removed the initialization of HashMap

        for (Element link : links) {
            String linktext = link.text();

            // ** Removed the onClickListener **

            Student student = new Student();
            student.setTitle(linktext);
            student.setLink(link);

            // Just add the items here
            linkList.add(student);
        }

        return linkList;

    } else {
        // The else part goes here
    }

    return null;
}

最后,在您的 AsyncTask 中,您需要像这样修改您的 onPostExecute 以通知您的 linkList 已填充数据,因此适配器刷新它。

private class GetLinks extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... arg0) {
        Document doc;
        Elements links;

        try {
            doc = Jsoup.connect(url).get();
            links = doc.getElementsByClass("processlink");
            linkList = ParseHTML(links);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        // Just call the notifyDatasetChanged to notify the adapter 
        // to reload the data from the linkList
        adapter.notifyDatasetChanged();
    }
}

更新

@PanveetSingh 表示,student 不是一个对象,而是一个HashMap。对不起,我之前错过了那部分。您可能会考虑像这样创建一个名为 Student 的类。

public class Student {
    public String title;
    public String linkhref;

    public Student() {}

    public void setTitle(String title) {
        this.title = title;
    }

    public void setLink(Element link) {
        this.linkhref = "http://" + link.select("a").attr("href");
    }

    public String getTitle() {
        return this.title;
    }

    public String getLink() {
        return this.linkhref;
    }
}

您的ParseHTML 函数和其他函数已相应修改。

关于Android ListView 项目点击不会转到正确的屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41245742/

相关文章:

android - 破坏移动设备上的 Google Analytics session

Java解析JS生成的html元素

java - 我应该如何修改来解析Google新闻搜索文章标题和预览和URL?

groovy - 如何使用groovy解析xml

android - 在禁用 dexpreopt 的情况下构建单独的 Android 模块

android - 任务 :appprocessDebugManifest. 执行失败 list 合并失败。有关更多信息,请参见控制台

java - 如何修复 SSLProtocolException : handshake alert: unrecognized_name without disabling SNI

java - 如何使用 jSoup 从 Java 模拟 Web 浏览器

android - 具有延迟的android Action 序列

java - Android:包含文件的空 Assets 文件夹