Android在布局中动态添加view的两种方法

通过xml文件定义layout

  1. 构建XML布局文件
  2. LayoutInflater

提到addview,首先要了解一下LayoutInflater类。这个类最主要的功能就是实现将xml表述的layout转化为View的功能。为了便于理解,我们可以将它与findViewById()作一比较,二者都是实例化某一对象,不同的是findViewById()是找xml布局文件下的具体widget控件实例化, 而LayoutInflater找res/layout/下的xml布局文件来实例化的。

  1. 创建LayoutInflater的三个方法

    • LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)
    • LayoutInflater inflater = LayoutInflater.from(Activity.this)
    • LayoutInflater inflater = getLayoutInflater();
      本质上是相同的 所以如果是在继承了Context的子类中 直接使用第三种方法比较快捷 其他的地方则需要传入上下文Context
  2. inflate()创建View的实例

用LayoutInflater.inflate() 将LayOut文件转化成VIew。View view = inflater.inflate(R.layout.block_gym_album_list_item, null);

测试代码

Content_main.xml




    

item.xml






MainActivity

public class MainActivity extends AppCompatActivity {
Button btn;
Button submit_java;
Button Clear_All;
LinearLayout ll;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ll = (LinearLayout) findViewById(R.id.ll_layout);
    final LayoutInflater inflater = getLayoutInflater();

    btn = (Button) findViewById(R.id.submit);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            View view = inflater.inflate(R.layout.item, null);
            ll.addView(view);
        }
    });

    submit_java = (Button) findViewById(R.id.submit_java);

    submit_java.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            LinearLayout layout = new LinearLayout(MainActivity.this);
            layout.setLayoutParams(params);
            layout.setOrientation(LinearLayout.HORIZONTAL);

            TextView tv1 = new TextView(MainActivity.this);

            TextView tc2 = new TextView(MainActivity.this);

            tv1.setLayoutParams(params);
            tc2.setLayoutParams(params);
            tv1.setText("livvy");
            tc2.setText("wukong");
            tc2.setPadding(20, 0, 0, 0);
            layout.addView(tv1
            );
            layout.addView(tc2);
            ll.addView(layout);

        }
    });
    Clear_All = (Button) findViewById(R.id.Clear_All);
    Clear_All.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ll.removeAllViews();
        }
    });
  }
}

你可能感兴趣的:(Android开发)