【问题标题】:Changing Action bar title on button click单击按钮时更改操作栏标题
【发布时间】:2014-03-05 12:43:15
【问题描述】:
我有两个Activity,activity1和activity2,activity1有两个按钮,button1和button2。当点击 button1 时,它应该链接到 activity2,在 Action-bar 中的标题应该是“am button1”,当点击 button2 时,它会再次链接到 activity2,并且它应该在 Action-bar 中的标题是“am button2”。
- 当 button1 单击 Activity1 时,它应该通过 put-extra 的 Intent 传递数据,并更改 Activity 操作栏标题为“am button1”。
- Activity2 应该从 activity1 接收数据并更改其中的操作栏。
请任何人帮我做这件事。
【问题讨论】:
标签:
android
android-actionbar
【解决方案1】:
活动一课
public class ActivityOne extends Activity{
Button btnOne, btnTwo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
btnOne = (Button) findViewById(R.id.btnOne);
btnOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("title", "am Button1");
startActivity(intent);
}
});
btnTwo = (Button) findViewById(R.id.btnTwo);
btnOne.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("title", "am Button2");
startActivity(intent);
}
});
}
}
ActivityTwo 类
public class ActivityTwo extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String title = intent.getStringExtra("title");
getActionBar().setTitle(title);
}
}
【解决方案2】:
这是你的解决方案
活动 1:点击任何按钮 1
Intent intent=new Intent(this,ActivityTwo.class);
intent.putExtra("title", "M button 1");
startActivity(intent);
活动 1:点击任何按钮 1
Intent intent=new Intent(this,ActivityTwo.class);
intent.putExtra("title", "M button 2");
startActivity(intent);
现在开始活动 2:
String title=getIntent().getStringExtra("title");
getActionBar().setTitle(title);
或
String title=getIntent().getStringExtra("title");
getSupportActionBar().setTitle(title);
【解决方案3】:
在第一个活动中
Intent mIntent;
@Override
public void onClick(View v) {
mIntent = new Intent(FirstActivity.this,SecondActivity.class);
switch (v.getId()) {
case R.id.first_btn:
mIntent.putExtra("buttonClicked", "Am Button One");
break;
case R.id.second_btn:
mIntent.putExtra("buttonClicked", "Am Button Second ");
break;}
startActivity(mIntent);}
//and in the second activity write:
private String mSelectedButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
mSelectedButton = getIntent().getIntExtra("buttonClicked", "");
}
然后使用变量mSelectedButton来设置标题
【解决方案4】:
在清单文件中声明您的第二个活动时,将您所需的名称设置为标签:
<activity
android:name="your second activity"
android:label="@string/your 2nd activity name" >
</activity>