簡體   English   中英

如何在另一個布局的按鈕上設置監聽器?

[英]How to set Listener on Button from another layout?

我在fragment_user布局中有按鈕( @+id/signOutButton )。 我想在我的LoginActivity的那個按鈕上設置 OnClickListener 。 這就是我的活動的樣子:

public class LoginActivity extends BaseActivity implements
        View.OnClickListener {

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // Button listeners
        findViewById(R.id.signInButton).setOnClickListener(this);
        findViewById(R.id.signOutButton).setOnClickListener(this); <<< this line already is crashing my app
        findViewById(R.id.disconnectButton).setOnClickListener(this);

在此代碼setOnClickListener我的應用程序崩潰。

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

如何修復它? 謝謝。

先給其他 xml 文件充氣:

LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.fragment_user, null);

然后從膨脹視圖中獲取對 Button 的引用並設置 OnClickListener:

Button signout = (Button)view.findViewById(R.id.signOutButton);
 signout.setOnClickListener( 
 //your code
 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM