我有8个按钮,每个按钮都会带您进行相同的活动,但活动的标题会根据您按下的按钮而改变。
这背后的想法是我有8个电影屏幕,每个按钮对应一个屏幕(1到8)。因此,在onclick方法中,我将对该屏幕使用正确的查询,并将标题设置为该特定的屏幕编号。有更好的方法可以做到这一点,就像下拉列表一样,但我只是想知道我已经拥有的东西。
有没有办法用@string参考设置页面的标题,还是我需要在按钮的onclick方法中对标题进行硬编码?
答案 0 :(得分:2)
如果我理解正确,您希望从java代码而不是xml访问字符串资源。您可以使用生成的R类来完成此操作。
E.g。 R.string.my_title
。这将为您提供该特定条目的资源ID。如果您想获取它的字符串值,请致电Context.getString(R.string.my_title)
。
有关详细信息,请参阅http://developer.android.com/guide/topics/resources/accessing-resources.html#ResourcesFromCode
答案 1 :(得分:2)
只需点击
即可传递文字public void onClick(View v)
{
String title = ((Button).getText();
Intent i = new Intent(MainActivity.this, NextActivitiy.class);
i.putExtra("title", title);
startActivity(i);
}
这假设您所指的String resource
是Button
的文本。您必须以这种或那种方式发送标题,以便这样做。
然后在你的下一个Activity
使用类似
Intent intent = getIntent();
String title = intent.getStringExtra("title");
答案 2 :(得分:0)
想出了我想要的方式。如果有人有任何其他想法,我愿意改变它。我是Android编程的新手,所以我可能不理解它。但这是我的解决方案。
public void theaterOneButtonOnClick(View v) {
String title = ("" + R.string.theater_number1);
Intent i = new Intent(MainActivity.this, TheaterActivity.class);
i.putExtra("title", title);
startActivity(i);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.theater_activity);
Intent intent = getIntent();
String sTitle = intent.getStringExtra("title");
TextView msgTextView = (TextView) findViewById(R.id.textView1);
int title = Integer.parseInt(sTitle);
msgTextView.setText(title);
}
}