[英]How can I get a textview to appear below another textview? Android
[英]Android::findViewByID - how can I get View of a TextView through a Listener of another UI element?
這將是一個有點蹩腳的問題。 我有以下代碼:
..............
public void onCreate (Bundle bundle)
{
super.onCreate(bundle);
this.setContentView(R.layout.main2);
Button bnt = (Button) this.findViewById(R.id.browser);
bnt.setOnClickListener(new ButtonListener());
}
..............
class ButtonListener implements android.view.View.OnClickListener
{
public void onClick(View v)
{
// I have a TextView in my xml layout file.
// I'd like to get it and change my text when I click this button.
// But I can't get it (the TextView) unless I make it as a value of a static member of this class and pass it to the constructor.
//I believe I am missing a big point here, so i'd be very thankful if you could explain how this is meant to be done ?
}
}
任何幫助表示贊賞。
你可以試試這個:
class ButtonListener implements android.view.View.OnClickListener {
public void onClick(View v) {
View parent = (View)v.getParent();
if (parent != null) {
TextView txtView = parent.findViewById(R.id.mytextview);
txtView.setText(...);
}
}
}
用法取決於您的布局。 可能的話,您的按鈕的父級不是您的textview的父級,所以要小心......
class ButtonListener implements android.view.View.OnClickListener {
public void onClick(View v) {
View p = (View) view.getRootView();
if (p != null) {
TextView txtView = (TextView) p.findViewById(R.id.mytextview);
txtView.setText(...);
}
}
}
我需要設置一個來自同一個父元素的元素,所以我使用了這個代碼:)並且它有效
編輯我不認為這是可能的。 視圖V中只有按鈕視圖....
你會知道你是否相同
class ButtonListener implements android.view.View.OnClickListener
{
public void onClick(View v)
{
Button vg=(Button)v;
Log.e("", "views are "+vg.getText());
//但是你可以在這里為ue textview txt.setText設置測試(“改變文本”);
}
}
我沒有正確理解你的問題。 但是,如果你只想從你的TextView中獲取文本,你可以嘗試這樣
TextView txt;
public void onCreate (Bundle bundle)
{
super.onCreate(bundle);
this.setContentView(R.layout.main2);
Button bnt = (Button) this.findViewById(R.id.browser);
txt=(TextView)this.findViewById(R.id.urtextview);
bnt.setOnClickListener(new ButtonListener());
}
..............
class ButtonListener implements android.view.View.OnClickListener
{
public void onClick(View v)
{
// I have a TextView in my xml layout file.
// I'd like to get it and change my text when I click this button.
// But I can't get it (the TextView) unless I make it as a value of a static member of this class and pass it to the constructor.
//I believe I am missing a big point here, so i'd be very thankful if you could explain how this is meant to be done ?
//I think this should get u the string...
System.out.println("text is "+txt.getText().toString());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.