Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android動態添加設置布局與控件的方法

Android動態添加設置布局與控件的方法

編輯:關於Android編程

本文實例講述了Android動態添加設置布局與控件的方法。分享給大家供大家參考,具體如下:

有時候我們會在代碼端,動態的設置,添加布局和控件。下面我們就看來看一下如何處理,直接上代碼,代碼裡面的注解很清楚了。

布局文件:fragment_hot.xml

說明:這個部局,我用的是scrollView做為基礎布局,主要是為了實現一個滾動。這裡不多說,這個你可以使用任何布局都可以,這裡的id我是提前定義的。

這裡面的現在有的布局是我為了看到我在代碼端,動態添加的代碼,是否可以追加到現有布局的後面而加上,這裡大家可以自己設置

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@id/id_stickynavlayout_innerscrollview"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <LinearLayout
    android:id="@+id/line_fragment_hot_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="80dp"
      android:orientation="horizontal">
      <LinearLayout
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_weight="1">
        <ImageView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:src="@drawable/desktop_device"/>
      </LinearLayout>
      <LinearLayout
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_weight="1"
        android:orientation="vertical">
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="燕郊孔雀城"/>
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="燕郊 燕郊"/>
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="3萬抵6萬"/>
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="6000元/m"/>
      </LinearLayout>
      <LinearLayout
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_weight="1"
        android:gravity="right">
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="剩2天"
          android:textColor="#F97F49"
          android:textSize="12dp"
          android:text
          android:layout_marginTop="2dp"/>
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:background="@drawable/rectangle_radius_fen"
          android:gravity="center"
          android:text="團"
          android:textSize="9dp"
          android:textColor="#ffffff"
          android:layout_marginRight="5dp"
          android:layout_marginLeft="2dp"/>
      </LinearLayout>
    </LinearLayout>
    <LinearLayout
      android:layout_width="fill_parent"
      android:layout_height="80dp"
      android:orientation="horizontal">
      <LinearLayout
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_weight="1">
        <ImageView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:src="@drawable/desktop_device"/>
      </LinearLayout>
      <LinearLayout
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_weight="1"
        android:orientation="vertical">
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="燕郊孔雀城"/>
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="燕郊 燕郊"/>
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="3萬抵6萬"/>
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="6000元/m"/>
      </LinearLayout>
      <LinearLayout
        android:layout_width="0dp"
        android:layout_height="70dp"
        android:layout_weight="1"
        android:gravity="right">
        <TextView
          android:layout_width="wrap_content"
          android:layout_height="20dp"
          android:text="剩2天"/>
        <TextView
          android:layout_width="10dp"
          android:layout_height="10dp"
          android:background="@drawable/rectangle_radius_fen"
          android:gravity="center"
          android:text="團"
          android:textSize="5dp"
          android:layout_marginRight="5dp"/>
      </LinearLayout>
    </LinearLayout>
  </LinearLayout>
</ScrollView>

一個背景圖文件在drawable文件夾中

rectangle_radius_fen.xml

說明:很簡單,就是設置一個有圓角的方形

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle" >
  <!-- 定義填充漸變顏色 -->
  <solid android:color="#F97F49"/>
  <!-- 設置內填充 -->
  <padding android:left="1dp"
    android:top="1dp"
    android:right="1dp"
    android:bottom="1dp"/>
  <!-- 設置圓角矩形 -->
  <corners android:radius="2dp"/>
</shape>

後台代碼:

fragment_hot.java

說明:這裡不多說了,裡面的注解很明確了

package com.example.cg.fangduo;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
/**
 * A simple {@link Fragment} subclass.
 */
public class fragment_hot extends Fragment {
  //定義當前頁面
  private View view;
  private LinearLayout line_fragment_hot_main;
  private ScrollView id_stickynavlayout_innerscrollview;
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
               Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_hot, container, false);
    id_stickynavlayout_innerscrollview = (ScrollView)view.findViewById(R.id.id_stickynavlayout_innerscrollview);
    line_fragment_hot_main = (LinearLayout)view.findViewById(R.id.line_fragment_hot_main);
    for(int i=0;i<10;i++) {
      /**
       * 設置每個item最外層的LinearLayout
       */
      LinearLayout itemMain = new LinearLayout(getActivity());
      itemMain.setOrientation(LinearLayout.HORIZONTAL); //設置linearLayout是橫向還是豎各
      LinearLayout.LayoutParams itemMainparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(getActivity(), 80)); //設置寬與高
      itemMainparams.setMargins(0,dip2px(getActivity(),1),0,0); //設置每個item與上一個控件的間隔是1dip
      itemMain.setLayoutParams(itemMainparams);
      itemMain.setBackgroundColor(Color.WHITE); //設置背景色
      itemMain.setVerticalGravity(Gravity.CENTER); //設置對齊方式
      /**
       * 設置左側圖片LinearLayout
       */
      LinearLayout itempic = new LinearLayout(getActivity());
      itempic.setOrientation(LinearLayout.HORIZONTAL);
      LinearLayout.LayoutParams itempicparams = new LinearLayout.LayoutParams(0, dip2px(getActivity(), 70), 1);
      itempic.setLayoutParams(itempicparams);
      itempic.setVerticalGravity(Gravity.CENTER_VERTICAL);
      /**
       * 設置圖片
       */
      ImageView imgPic = new ImageView(getActivity());
      imgPic.setImageResource(R.drawable.desktop_device);
      LinearLayout.LayoutParams imgPicparams = new LinearLayout.LayoutParams(dip2px(getActivity(), ViewGroup.LayoutParams.WRAP_CONTENT), dip2px(getActivity(), ViewGroup.LayoutParams.WRAP_CONTENT));
      imgPicparams.leftMargin = dip2px(getActivity(), 5);
      imgPicparams.gravity = Gravity.LEFT;  //必須要加上這句,setMargins才會起作用,而且此句還必須在setMargins下面
      imgPic.setLayoutParams(imgPicparams);
      /**
       * 圖片LinearLayout加載圖片
       */
      itempic.addView(imgPic, imgPicparams);
      /**
       * 向主LinearLayout加載圖片LinearLayout
       */
      itemMain.addView(itempic);
      /**
       * 設置中間文字顯示LinearLayout
       */
      LinearLayout itemtext = new LinearLayout(getActivity());
      itemtext.setOrientation(LinearLayout.VERTICAL);
      LinearLayout.LayoutParams itemtextparams = new LinearLayout.LayoutParams(0, dip2px(getActivity(), 70), 1);
      itemtext.setLayoutParams(itemtextparams);
      itemtext.setVerticalGravity(Gravity.CENTER_VERTICAL);
      TextView txtOne = new TextView(getActivity());
      txtOne.setText("珠江俊景小區");
      txtOne.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12); //設置字號,並且設置它的單位為dip
      txtOne.getPaint().setFakeBoldText(true); //字體加租
      LinearLayout.LayoutParams txtOneparams = new LinearLayout.LayoutParams(dip2px(getActivity(), ViewGroup.LayoutParams.WRAP_CONTENT), dip2px(getActivity(), ViewGroup.LayoutParams.WRAP_CONTENT));
      txtOneparams.weight = 1;
      txtOneparams.setMargins(0, 0, 0, 0);
      txtOneparams.gravity = Gravity.LEFT;
      txtOne.setLayoutParams(txtOneparams);
      itemtext.addView(txtOne);
      TextView txtTwo = new TextView(getActivity());
      txtTwo.setText("哈爾濱");
      txtTwo.getPaint().setFakeBoldText(true);
      txtTwo.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 8);
      LinearLayout.LayoutParams txtTwoparams = new LinearLayout.LayoutParams(dip2px(getActivity(), ViewGroup.LayoutParams.WRAP_CONTENT), dip2px(getActivity(), ViewGroup.LayoutParams.WRAP_CONTENT));
      txtTwoparams.weight = 1;
      txtTwo.setLayoutParams(txtTwoparams);
      itemtext.addView(txtTwo);
      TextView txtThree = new TextView(getActivity());
      txtThree.setText("一萬抵五萬");
      txtThree.getPaint().setFakeBoldText(true);
      txtThree.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 8);
      txtThree.setLayoutParams(txtOneparams);
      itemtext.addView(txtThree);
      TextView txtFour = new TextView(getActivity());
      txtFour.setText("8000元/m");
      txtFour.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10);
      txtFour.setTextColor(Color.parseColor("#F97F49"));
      txtFour.getPaint().setFakeBoldText(true);
      txtFour.setLayoutParams(txtOneparams);
      itemtext.addView(txtFour);
      itemMain.addView(itemtext);
      /**
       * 定義右側顯示信息框架
       */
      LinearLayout line_right_text = new LinearLayout(getActivity());
      line_right_text.setOrientation(LinearLayout.HORIZONTAL);
      LinearLayout.LayoutParams rightparams = new LinearLayout.LayoutParams(0, dip2px(getActivity(), 70), 1);
      line_right_text.setLayoutParams(rightparams);
      line_right_text.setGravity(Gravity.RIGHT);  //右對齊
      TextView daytxt = new TextView(getActivity());
      LinearLayout.LayoutParams daytxtparams = new LinearLayout.LayoutParams(dip2px(getActivity(), ViewGroup.LayoutParams.WRAP_CONTENT), dip2px(getActivity(), ViewGroup.LayoutParams.WRAP_CONTENT));
      daytxt.setLayoutParams(daytxtparams);
      daytxt.setText("剩2天");
      daytxt.setTextColor(Color.parseColor("#F97F49")); //設置顏色
      daytxt.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 10); //設置文字大小
      daytxt.getPaint().setFakeBoldText(true); //設置文字樣式,加粗
      //daytxt.setPadding(0,2,2,0);
      line_right_text.addView(daytxt);
      TextView tuantxt = new TextView(getActivity());
      LinearLayout.LayoutParams tuantxtparams = new LinearLayout.LayoutParams(dip2px(getActivity(), 12), dip2px(getActivity(), 12));
      tuantxtparams.setMargins(dip2px(getActivity(), 2), dip2px(getActivity(), 0), dip2px(getActivity(), 5), 0);
      tuantxt.setLayoutParams(tuantxtparams);
      tuantxt.setBackgroundResource(R.drawable.rectangle_radius_fen);  //設置textView背景圖片
      tuantxt.setGravity(Gravity.CENTER);
      tuantxt.setText("團");
      txtFour.getPaint().setFakeBoldText(true);
      tuantxt.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 8);
      tuantxt.setTextColor(Color.parseColor("#ffffff"));
      line_right_text.addView(tuantxt);
      itemMain.addView(line_right_text);
      line_fragment_hot_main.addView(itemMain);
    }
    return view;
  }
  /**
   * 設備像素(dip,dp)轉屏幕像素(px)
   * px就是像素,如果用px,就會用實際像素畫,比個如吧,用畫一條長度為240px的橫線,在480寬的模擬器上看就是一半的屏寬,而在320寬的模擬器上看就是2/3的屏寬了。
       * 而dip,就是把屏幕的高分成480分,寬分成320分。比如你做一條160dip的橫線,無論你在320還480的模擬器上,都是一半屏的長度。
   * @param context
   * @param dipValue
   * @return
   */
  public static int dip2px(Context context, float dipValue){
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int)(dipValue * scale + 0.5f);
  }
  /**
   * 將px值轉換為sp值,保證文字大小不變
   *
   * @param pxValue
   * @param pxValue
   *      (DisplayMetrics類中屬性scaledDensity)
   * @return
   */
  public static int px2sp(Context context, float pxValue) {
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int) (pxValue / fontScale + 0.5f);
  }
  /**
   * 將sp值轉換為px值,保證文字大小不變
   *
   * @param spValue
   * @param spValue
   *      (DisplayMetrics類中屬性scaledDensity)
   * @return
   */
  public static int sp2px(Context context, float spValue) {
    final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
    return (int) (spValue * fontScale + 0.5f);
  }
}

效果圖:

希望本文所述對大家Android程序設計有所幫助。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved