Android ListView项目单击没有转到右侧屏幕

时间:2016-12-20 15:23:24

标签: 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" />

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

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

2 个答案:

答案 0 :(得分:1)

我想,linkList已在全球宣布。所以你可以这么做。

我很乐意建议您在代码中进行一些编辑。您可以在ListView功能中完全初始化onCreate。将您的Adapter声明为全局变量。

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

// 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功能和其他功能也会相应修改。

答案 1 :(得分:0)

使用ParseHTML(Elements links)方法

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

linkList也必须是final

(还要记住,在Java中,methodNamesShouldBeInThisFormat()