OnClick 导航抽屉标题不起作用 [英] OnClick for navigation drawer header not working
问题描述
我的应用中有一个导航抽屉,其中包含一个标题和一些列表项.标题有一个文本视图,我想使其可点击,但我无法做到.
I have a navigation drawer in my app which contains a header and some list items. The header has a textview which i want to make clickable but I am not able to do it.
为了获取这个 textview 的 id,我使用了以下代码,因为与 onCreate 中的 setContentView 中的布局文件相比,它位于不同的布局文件中.
To get the id of this textview I used the following code, since it is in a different layout file compared to the one in the setContentView in onCreate.
final LayoutInflater factory = getLayoutInflater();
final View textEntryView = factory.inflate(R.layout.header, null);
TextView home = (TextView) textEntryView.findViewById(R.id.home);
home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(curr_context, "SHOW", Toast.LENGTH_LONG).show();
}
});
header.xml 包含导航抽屉的标题.它有一个名为 home 的项目.我需要让它可点击.以上代码在onCreate方法中.
header.xml contains the header of the navigation drawer. It has an item named home. I need to make it clickable. The above code is in the onCreate method.
推荐答案
对我来说,其他答案不起作用.我试过下面的代码.我知道为时已晚.希望这会有所帮助.
For me other Answers didn't work. I have tried the below code. I know it's too late. Hope this will help some.
我做了什么来访问标题视图.
What I did to access the view of header.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerview = navigationView.getHeaderView(0);
TextView profilename = (TextView) headerview.findViewById(R.id.prof_username);
profilename.setText("your name")
为了点击header的views,这里我使用了headerview的linearlayout
for clicking the views of header, here I have used a linearlayout of headerview
LinearLayout header = (LinearLayout) headerview.findViewById(R.id.header);
header.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(HomeActivity.this, "clicked", Toast.LENGTH_SHORT).show();
drawer.closeDrawer(GravityCompat.START);
}
});
或者
headerview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Your code here
}
});
这篇关于OnClick 导航抽屉标题不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!