如何在不同的Activity中控制其他View?

时间:2016-08-26 19:40:58

标签: android listview listview-adapter

我创建了<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/> <xsl:template match="/test"> <xsl:copy> <players> <xsl:for-each-group select="*/person" group-by="name"> <person> <xsl:copy-of select="name"/> <xsl:copy-of select="current-group()/*[not(self::name)]"/> </person> </xsl:for-each-group> </players> </xsl:copy> </xsl:template> </xsl:stylesheet> 的customAdapter。当我点击ListView中的Button时,我想从不同的布局控制ListView之外的TextView。注意 !没有相同的Java代码。

这就是我想要做的事情:

ListView

2 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点我记得3:

1)将TextView添加到ListView适配器构造函数的参数

2)将Activity添加到构造函数

3)使用基于事件的解决方案,例如EventBus [这可以在不同的活动中用于您的TextViewListView,而且您不需要参数]

有1和2的例子:

public class YourListAdapter{

TextView strangerTextView;
YourActivity yourActivity;

public YourListAdapter(TextView strangerTextView,Activity yourActivity){
   //using one of them is enough
   this.strangerTextView=strangerTextView;
   this.yourActivity=yourActivity;
}
//when changing text use like 

strangerTextView.setText("Class Board");

//or (make sure you have global public textview attribute in your YourActivity class)

yourActivity.textview.setText("Class Board");


}

EventBus

1)创建一个包含事件信息的类:

public class TextChangeEvent{
    public String newtext;
    public TextChangeEvent(String newtext){
        this.newtext=newtext;
    }
}

2)然后在您的相关活动中:

@Override
protected void onStart() {
    super.onStart();
    if(!EventBus.getDefault().isRegistered(this))EventBus.getDefault().register(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    EventBus.getDefault().unregister(this);

}

@Subscribe
public void onEvent(TextChangeEvent event) {
    this.textView.setText(event.newtext)
}

3)在任何地方发布这样的事件:

EventBus.getDefault().post(new TextChangeEvent("newtext"));

答案 1 :(得分:-2)

您的TextView是否在同一个活动中?如果是,那么你应该把

tx = (TextView) findViewById(R.id.moneytext);

在onCreate()方法中,然后从你拥有的侦听器访问它:

tx.setText("" + totalmoney);

如果不是同一个活动,你可以这样做:

public class ClassA extends Activity
{
    public TextView textView;

    public void onCreate()
    {
        super.onCreate();
        textView = (TextView) findViewById(R.id.moneytext);
    }
}

public class ClassB extends Activity
{
    ...
        viewHolder.plus.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        //classA is a global variable that you get for example from contructor
        tx = classA.textView;

        totalmoney= (Integer.parseInt(tx.getText().toString()))+(Integer.parseInt(price[position])); 
         //get the textview integer and add to my present number

        tx.setText(""+totalmoney);
         //post on the textview

    }
});
    ...
}