我有以下方法,我想显示Snackbar
。问题是,我没有活动view
而且我不知道如何获得它。在代码中,您会看到Snackbar view
是viewInflate_setup
,但它不起作用。我知道它不起作用,因为这是我alertdialog
的视图而不是我当前的屏幕。我已尝试获取root view
,但snackbar
显示在错误的位置(在这三个Android按钮后面)。如何获得我的活动View
?
public void confirmPassword(){
final LayoutInflater inflateSetup = getLayoutInflater();
final View viewInflate_setup = inflateSetup.inflate(R.layout.inflate_setup, null);
AlertDialog.Builder alertSetup = new AlertDialog.Builder(this);
alertSetup.setView(viewInflate_setup);
final AlertDialog dialogSetup = alertSetup.create();
dialogSetup.show();
btnConfirmPassowod = (Button)viewInflate_setup.findViewById(R.id.btnConfirm);
btnConfirmPassowod.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
System.out.println("User has clicked the [confirm] button");
dialogSetup.setCancelable(false);
edtPassword3 = (EditText)viewInflate_setup.findViewById(R.id.edtPassword3);
SUpassword3 = edtPassword3.getText().toString();
final ParseUser beforeConfirmPassword = ParseUser.getCurrentUser();
ParseUser.logInInBackground(beforeConfirmPassword.getUsername(), SUpassword3, new LogInCallback() {
@Override
public void done(ParseUser parseUser, ParseException e) {
if(e==null){
//password confirmed, go to next setup
System.out.println("Password [" +SUpassword3+ "] and user [" +beforeConfirmPassword.getUsername()+ "] confirmed, go to setup");
dialogSetup.dismiss();
}else{
//passwords don't match
System.out.println("Password don't match: [" +SUpassword3 + "] USER [" +beforeConfirmPassword.getUsername()+ "]");
Snackbar.make(viewInflate_setup, "Wrong password. Try again.", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
dialogSetup.dismiss();
}
}
});
}
});
}
答案 0 :(得分:6)
您可以使用findViewById(android.R.id.content)
或getWindow().getDecorView()
来获取您的活动的根视图
即Snackbar.make(findViewById(android.R.id.content), "Wrong password. Try again.", Snackbar.LENGTH_LONG).show();
将完成这项工作。
答案 1 :(得分:4)
您唯一需要的是设置id
根视图并创建它的实例。
<强> activity_main.xml中强>
<LineaLayout
...
android:id="my_root">
...
</LinearLayout>
MainActivity
private LinearLayout mRootView;
onCreate(...){
...
mRootView = (LinearLayout) findViewById(R.id.my_root);
...
}
并且,在您的警报对话框中,只需创建一个小吃吧,如:
Snackbar.make(mRootView, "Wrong password. Try again.", Snackbar.LENGTH_LONG).setAction("Action", null).show();