Java dynamically adds view methods

  • 2020-06-01 09:49:36
  • OfStack

In general, most of us write layout directly in XML file, but sometimes we need to use code to add layout dynamically. For example, I made a page display of viewpager yesterday. When there is no content, textView is dropped to clear, while there is content, Java is added dynamically.

1. Write code to generate view and add it to linearLayout.


mTextView=new TextView(mActivity);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(60, 30);
mTextView.setLayoutParams(layoutParams);
mTextView.setTextColor(Color.parseColor("#03A9F4"));
mTextView.setVisibility(View.GONE);
dotsLinearLayout.addView(mTextView);

2. Display textView according to the page change of viewpager


public void setCurrentNumber(int number){
  boolean isContain=false;
  for(int i=0;i<dotsLinearLayout.getChildCount();i++){
   View v=dotsLinearLayout.getChildAt(i);
   if (v instanceof TextView){
     isContain=true;
   }
  }
  if (isContain == false){
   setMTextView();
  }
  if (myViewPagerAdapter!=null){
   int current=number+myViewPager.getCurrentItem()*4;
   mTextView.setText(current+"/"+myViewPagerAdapter.getCount()*4);
   mTextView.setVisibility(View.VISIBLE);
   for (int i = 0; i < dotViews.size(); i++) {
      dotViews.get(i).setVisibility(View.GONE);
   }
  }
}

The for loop determines whether textView exists in linearlayout, and if it does not, textView is created, and then the data of textView can be changed dynamically.


Related articles: