Search code examples
androidandroid-relativelayout

change property of a relative layout field programmatically


I am working on an Android application.In my app I have change the textview alignment dynamically. The textview is in relativelayout. the following is my sample xml file

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/all"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
>
<TextView android:id="@+id/snt_txt"
android:layout_width="wrap_content" 
 android:layout_height="wrap_content"
 android:background="@color/Gold"   
 android:text="df"  
 android:layout_marginLeft="5dp"
 android:layout_marginRight="5dp"
 android:padding="3dp"/>
</RelativeLayout>

And in java i did the following

View vi = inflater.inflate(R.layout.smsconversationsent_row, null);
 RelativeLayout nws=(RelativeLayout)vi.findViewById(R.id.all);
 TextView   message=(TextView)vi.findViewById(R.id.snd_txt);
RelativeLayout.LayoutParams params=(RelativeLayout.LayoutParams)message.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        message.setLayoutParams(params);

But I am getting nullpointer exception for message.getlayoutparams().


Solution

  • Reason of nullpointer exception is the following: You're trying to find R.id.snd_txt, but in layout You have snt_txt, so it's impossible to find view with snd_txt id, because it doesn't exists in the layout.