我该怎么办或代替getActivity()

时间:2015-11-10 23:35:59

标签: android android-activity

我想将值发送到onFinishEditDialog,但我不知道该怎么做。 请帮帮我或你有其他方法吗?

public  String strhashtag;
public interface EditNameDialogListener {
    void onFinishEditDialog(String inputText);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.hashtaglayout);
    Intent hashtag = getIntent();
    strhashtag = hashtag.getStringExtra("hashtag");

    Button btnendhashtag = (Button) findViewById(R.id.btnendhashtag);


    btnendhashtag.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditNameDialogListener activity = (EditNameDialogListener) getActivity();
            activity.onFinishEditDialog(strhashtag);
            finish();
        }
    });

}

1 个答案:

答案 0 :(得分:0)

将GreenRobot的EventBus添加到Gradle,如下所示:

compile 'de.greenrobot:eventbus:2.4.0'

然后,在EditNameDialogListener活动中,实例化它的实例

private EventBus bus;

onCreate {

    bus = EventBus.getDefault();
    bus.register(this);
}

onDestroy {

    bus.unregister(this);

}

创建一个FinishEditDialog类

public class FinishEventDialog() {
    // COnstructor, getters and setters for custom data you want to send over
}

在EditNameDialogListener活动中提供此方法:

public void onEvent(FinishEditDialogEvent event) {
    // do whatever you want here, extract data from the event
}

在您当前的活动中,向任何已注册的听众发布活动:

onClick {

    EventBus.getDefault().post(new FinishEditDialogEvent()); 
}