findviewbyid doesn't work in android
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class ViewId extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Text开发者_StackOverflow社区View txtArea = new TextView(this);
txtArea.setId(20);
txtArea.setText("Hello");
TextView view = new TextView(this);
view = (TextView) this.findViewById(20);
Toast.makeText(this,view.getText(), Toast.LENGTH_LONG).show();
}
}
When I debug above code in eclipse the value of view shows null in variable window. what is the problem? or is there any other method to setid of textview and and retrive that text view from that particular id without using XML file.
Your code is a bit messy. First you set your contentview with an xml layout, which you never use. You also create a TextView txtArea and set the id to 20, which is ok, but you never add this view to your content, so you can find it later, of course.
You have to decide: do your layout with XML and use it. You can also modify it programmatically or you create your own layout programmatically and set the content view to the new created layout/view.
精彩评论