从ClickListener传递字符串

时间:2019-02-17 16:17:00

标签: java android string listview onitemclicklistener

在我的活动中,我有一个HorizontalScrollView和九个TextViews,在下面有一个ListView。如果我单击九个TextViews中的一个,列表将刷新并显示一些存储在数据库中的数据,其值与TextView相同(这可以正常工作)。

现在,我单击一个ListItem,然后打开一个新活动。

在这里,我希望TextView中的值也将发送到新的Activity中。不幸的是,我不知道该怎么做,希望有人能帮助我。

这是我的代码的一部分:

dataSource = new ArrayList<>();

lvWP.setAdapter(new WPAdapter(this, dataSource));

horiView = (HorizontalScrollView) findViewById(R.id.horiView );
    lvWP.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Object element = parent.getAdapter().getItem(position);

            if (element instanceof Workpackage){
                Workpakage workpackage= (Workpakage ) element;

                Intent wp = new Intent(ProjektOverview.this, WorkpackageDetail.class);

                String projekt = tvProjectTitle.getText().toString();

                wp.putExtra(WorkpackageDetail.WP_KEY, workpackage.getId());
                wp.putExtra("DEPARTMENT", department);  //THIS SHOULD BE THE STRING FROM tvWKA
                wp.putExtra("PROJECTNAME", project);

                startActivity(wp);
            }
        }
    });

// HERE I CLICK ON ONE TEXTVIEW FROM THE HORIZONTALSCROLLVIEW 
tvWKA.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        String department= "WKA";  // THIS STRING I WANT TO SEND TO MY LISTVIEW ONCLICKLISTENER

        String project= tvProjectTitle.getText().toString();
        refreshList(department, projekt);
    }
});

public void refreshList(String department, String project) {
    dataSource.clear();
    dataSource.addAll(WorkpackageDB.getInstance(ProjectOverview.this).readAllAP(department, projekt));
    lvWP.invalidateViews();
}

1 个答案:

答案 0 :(得分:0)

selectedDepartment类中只能有一个像Activity这样的全局变量,当您单击TextView时可以填充该变量。

private String selectedDepartment; 

tvWKA.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        selectedDepartment = "WKA";  
        String project = tvProjectTitle.getText().toString();
        refreshList(department, projekt);
    }
});

然后,您可以在将意图传递给另一个活动时将其添加为附加项。

wp.putExtra(WorkpackageDetail.WP_KEY, workpackage.getId());
wp.putExtra("DEPARTMENT", selectedDepartment); // Here 
wp.putExtra("PROJECTNAME", project);

希望有帮助!