How to change a TextView's text from a custom View?
I'm actually trying to build my first a开发者_StackOverflow中文版ndroid app, and I just encountered a problem I can't figure out.
I have in my XML two views, one is a plain basic TextView :
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
and the other one is a custom class I built :
<com.package.testpanel.Panel
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
The code of this "Panel" is quite simple :
public class Panel extends View implements OnTouchListener, OnGestureListener {
TextView tv;
public Panel(Context context, AttributeSet attrs) {
super(context, attrs);
tv = (TextView) findViewById(R.id.tv);
if (tv != null) {
tv.setText("Text changed");
}
}
}
(I have of course implemented all the Listeners method)
As you can see in my constructor, I'm just trying to change the TextView's text from my Panel, and it won't work. If I don't put the "if (tv != null)" condition, the app just crash at launch. I tried putting this piece of code in one of the listener's method instead of the constructor, and it's the same result : nothing happen or it crashes without the if condition. If I put the exact same code in the Activity's onCreate, it works perfectly, but my goal is to change the text/properties of the TextView based on the touch and gesture listener on my panel.
I'm really new to this android SDK, I have yet to try how to debug an app, but for now I would just like to know why this simple code isn't working.
So if anyone has an idea as why I can't do that, or a work-around, I'd be much obliged !
Yes. We should first load the main layout before trying to get the sub-view. This is usually with following statement:
setContentView(R.layout.your_layout);
Please refer to http://developer.android.com/reference/android/app/Activity.html
Also I suggest you firstly spend some time on the basic concept before trying to create complicated app. This will save you lots of time to finger out those questions.
AddsetContentView(R.layout.your_filename_with_textview);
before tv = (TextView) findViewById(R.id.tv);
精彩评论