2013-04-18 4 views
2

В моем приложении у меня есть переговорная комната. Все мои сообщения должны быть выровнены вправо, а остальные должны быть выровнены влево.Android, Как получить/установить параметры макета?

Однорядные мой список, как это:

<?xml version="1.0" encoding="utf-8"?> 

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:id="@+id/llContainer" > 

    <LinearLayout 
     android:orientation="vertical" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_margin="5dp" 
     android:background="@drawable/speech_bubble_orange" 
     android:id="@+id/llGroup" > 

      <TextView 
       android:id="@+id/message_text" 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:shadowColor="@color/message_textShadow" 
       android:shadowDx="1" 
       android:shadowDy="1" 
       android:text="Medium Text" 
       android:textColor="@color/message_textColor" 
       android:textSize="20sp" /> 

      <TextView 
       android:id="@+id/message_date" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:text="@string/temp_date" 
       android:gravity="right" 
       android:layout_marginLeft="4dp" 
       android:layout_marginRight="4dp"/> 
    </LinearLayout> 

</LinearLayout> 

GetView() мой адаптер, как это:

@Override 
public View getView(final int position, View convertView, ViewGroup parent) { 
    ViewHolder holder; 

    if (convertView == null) { 
     convertView = myInflater.inflate(R.layout.list_message_row, null); 
     holder = new ViewHolder(); 

     holder.tvMessageBody = (TextView) convertView.findViewById(R.id.message_text); 
     holder.tvMessageDate = (TextView) convertView.findViewById(R.id.message_date); 
     holder.llContainer = (LinearLayout) convertView.findViewById(R.id.llContainer); 
     holder.llGroup = (LinearLayout) convertView.findViewById(R.id.llGroup); 

     convertView.setTag(holder); 
    } else { 
     holder = (ViewHolder) convertView.getTag(); 
    } 

    holder.tvMessageBody.setText(messageList.get(position).getMessageBody()); 
    String date = messageList.get(position).getSentDate(); 
    holder.tvMessageDate.setText(formatFanciedDate(date)); 

    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) holder.llContainer.getLayoutParams(); 
    try { 
     if(messageList.get(position).isMine()) { 
      holder.llGroup.setBackgroundResource(R.drawable.speech_bubble_green); 
      params.gravity = Gravity.RIGHT; 
     } 
     //If not mine then it is from sender to show orange background and align to left 
     else { 
      holder.llGroup.setBackgroundResource(R.drawable.speech_bubble_orange); 
      params.gravity = Gravity.LEFT; 
     } 

     holder.llContainer.setLayoutParams(params); 

    } catch (NullPointerException e) { 
     e.printStackTrace(); 
    } 

    return convertView; 
} 

Я думаю, что все должно быть хорошо, однако, когда я бегом NullPointerException приложения происходит и указывает на params.gravity = Gravity.RIGHT; или params.gravity = Gravity.LEFT; (зависит от метода isMine()).

Что вы думаете? Где моя ошибка? Любое предложение будет оценено по достоинству.

ответ

5

Используйте параметры RelativeLayout и установите гравитацию, как это, она будет работать.

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); 

Это работает для меня в моем приложении.

+0

Спасибо Радже, вы имеете в виду, что я меняю контейнер с LinearLayout на RelativeLayout? – Hesam

+0

да, и решит вашу проблему, я уверен. –

+0

+1 Ровно, спасибо вам через 3 часа, когда вы решили мою проблему. Спасибо;) – Hesam

5

getLayoutParams() вернет null, пока вид не будет прикреплен к его родительскому объекту.

Попробуйте создать параметры макета с помощью своего конструктора, а не использовать getLayoutParams().

+0

+1 да, вы правы. благодаря – Hesam

Смежные вопросы