i am relatively new to Android programming. i have gone through a lot of threads on this topic but none of the solutions mentioned work for me. Here is what i am trying.
i am trying to create a layout resource with an XML file and in my MainActivity, i do a setContentView(R.layout.activity_main). i then have a custom view class that extends View in which i try to modify the default layout defined in the activity_main.xml file.
However, any time i try to obtain a View Id with the findViewById(R.id.) (from the layout file activity_main.xml) in the Custom view implemented in a separate file, i always get null. If i try to get the id in the MainActivity class with the findViewById(...), i get a proper value.
What am i doing wrong here ?
Here are all the code snippets
thanks
Here is the file "MainActivity.java"
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyView myView = new MyView(this, null);
....
Here is the file MyView.java
public class MyView extends View {
public static final String DEBUG_TAG = "MYVIEW" ;
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
View tablerow1 = (TableRow) findViewById (R.id.tableRow) ;
Log.v(DEBUG_TAG," tablerow1 = " + tablerow1 + "\n");
}
And here is the file activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/top_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TableLayout
android:id="@+id/tableLayout1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="2"
android:background="@color/red"
android:shrinkColumns="*"
android:stretchColumns="*" >
<TableRow
android:id="@+id/tableRow1"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:gravity="center_horizontal">
<Button
android:id="@+id/button_00_1"
android:text="@string/button_1"
android:textStyle="bold"
android:background="@color/green"
android:layout_margin="0.5dp"
android:layout_width="0dp"
android:layout_weight="0.5"
android:typeface="serif"></Button>
</TableRow>
</TableLayout>
</LinearLayout>
The findViewById(...) call in the MyView.java always returns null, whereas if i include it in the MainActivity.java file, i get proper non-null values.
Can someone point out what is wrong here ?
thanks