【问题标题】:Access android custom ActionBar from Activity从Activity访问android自定义ActionBar
【发布时间】:2014-12-16 00:52:15
【问题描述】:

我创建了一个扩展 ActionBarActivity 并显示自定义 XML 的类。我几乎所有的活动都扩展了该课程。

我想从我的一项活动中访问该自定义 XML 的元素。假设我想在 Activity2 中更改 item2 的背景。

在我的activity的onCreate方法中,在setContentView之后,我尝试了:

View cView = getLayoutInflater().inflate(R.layout.custom_menu, null);
ImageButton rewards_link = (ImageButton) cView.findViewById(R.id.rewards_link);
rewards_link.setVisibility(View.GONE); // For test purpose

即使按钮 ID 看起来正确,更改也不适用。有什么想法吗?

【问题讨论】:

  • 刚刚膨胀的cView 与您添加到操作栏的内容有何关系?
  • 对不起,我不确定你的问题。我只是想访问我的自定义 ActionBar 然后隐藏其中一项。
  • 你为什么要夸大一个与你的操作栏无关的新布局?
  • 对不起,我可能解释得不好。我正在膨胀的 Layout 是我在 ActionBar 中设置的 customView (getActionBar().setCustomView(R.layout.custom_menu);)

标签: android android-actionbar android-custom-view


【解决方案1】:

如果您通过 getActionBar().setCustomView(R.layout.custom_menu);(或 AppCompat v21 的 getSupportActionBar())设置自定义视图,那么您可以直接使用 findViewById() 访问这些视图,因为视图是视图层次结构的一部分,就像添加的视图一样通过setContentView():

ImageButton rewards_link = (ImageButton) findViewById(R.id.rewards_link);
rewards_link.setVisibility(View.GONE); // For test purpose

【讨论】:

  • 谢谢,但是当我这样做时,rewards_link.setVisibility(View.GONE); 返回 NullPointerException。
【解决方案2】:

使用#getCustomView

View view =getSupportActionBar().getCustomView(); ImageButton imageButton =
 (ImageButton)view.findViewById(R.id.action_bar_back); imageButton.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v){ 
   // Your code here ...
  } 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多